I have a problem with has_and_belongs_to_many
in a Rails 4 app. The setup is as follows:
- A User can have several Roles
- A Role can have several Permissions
Since many Users can share the same Roles, and many Roles can share the same Permissions, and I don't need special connection models between them, I am using has_and_belongs_to_many
for both these relationships.
Here are the 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 are named as per convention:
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
Roles <-> Permissions works great, but Users <-> Roles seems to work only one way. I can attach Users to Roles, but not Roles to Users – the collection methods do not exist on the User objects. From the rails console:
> 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>
Any idea what could be going on here?
Update:
When I run User.has_and_belongs_to_many :roles
from the console, the association is correctly set up and I can run User.first.roles
without issue. It seems the association for some reason isn't set up when the application is bootstrapped.