I have a problem with has_and_belongs_to_manyin a Rails 4 application. The configuration is as follows:
- User can have multiple roles.
- A role can have multiple permissions.
Since many users can use the same roles, and many Roles can use the same Permissions, and I do not need special models of connections between them, I use has_and_belongs_to_manyfor both of these relationships.
Here are the models (devoid of validations):
class User < ActiveRecord::Base
has_and_belongs_to_many :roles
end
class Role < ActiveRecord::Base
has_and_belongs_to_many :permissions
has_and_belongs_to_many :users
end
class Permission < ActiveRecord::Base
has_and_belongs_to_many :roles
end
Association tables are named according to the agreement:
create_table "permissions_roles" do |t|
t.integer "role_id"
t.integer "permission_id"
end
create_table "roles_users" do |t|
t.integer "role_id"
t.integer "user_id"
end
↔ , ↔ , , . , - . rails:
> r = Role.first
> r.users
> u = User.first
> u.roles
, ?
Update:
User.has_and_belongs_to_many :roles , , User.first.roles . , - , .