ruby - Rails has_and_belongs_to_many collection methods not showing up on object -
i have problem has_and_belongs_to_many
in rails 4 app. setup follows:
- a user can have several roles
- a role can have several permissions
since many users can share same roles, , many roles can share same permissions, , don't need special connection models between them, using has_and_belongs_to_many
both these relationships.
here models (stripped 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
the join tables named per convention:
create_table "permissions_roles" |t| t.integer "role_id" t.integer "permission_id" end create_table "roles_users" |t| t.integer "role_id" t.integer "user_id" end
roles <-> permissions works great, users <-> roles seems work 1 way. can attach users roles, not roles users – collection methods not exist on user objects. rails console:
> r = role.first # fetch role > r.users # empty list of users -- far > u = user.first # fetch user > u.roles # nomethoderror: undefined method `roles' #<user:0x007fe67562f580>
any idea going on here?
update:
when run user.has_and_belongs_to_many :roles
console, association correctly set , can run user.first.roles
without issue. seems association reason isn't set when application bootstrapped.
maybe should consider using has_many, :through
here example
from 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
more ressources on:
Comments
Post a Comment