Rails has_and_belongs_to_many collection methods are not displayed on the object

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 # Fetch a role
> r.users        # Empty list of users -- so far so good
> u = User.first # Fetch a user
> u.roles        # NoMethodError: undefined method `roles' for #<User:0x007fe67562f580>

, ?

Update:

User.has_and_belongs_to_many :roles , , User.first.roles . , - , .

+4
2

, has_many,:

rubyonrails.org:

class Assembly < ActiveRecord::Base
  has_many :manifests
  has_many :parts, through: :manifests
end

class Manifest < ActiveRecord::Base
  belongs_to :assembly
  belongs_to :part
end

class Part < ActiveRecord::Base
  has_many :manifests
  has_many :assemblies, through: :manifests
end

:

0

, . , . , , , .

0

Source: https://habr.com/ru/post/1532804/


All Articles