Cameron Cameron - 1 month ago 7
Ruby Question

Rails ActiveRecord relationships for has_and_belongs_to_many

What would the correct relationships in Rails be for this setup:

users
id
name
email

roles
id
name

permissions
id
name

users_roles
id
user_id
role_id

roles_permissions
id
role_id
permission_id


I then have the following models:

class User < ActiveRecord::Base
end

class Role < ActiveRecord::Base
has_and_belongs_to_many :users, :join_table => 'users_roles'
end

class Permission < ActiveRecord::Base
has_and_belongs_to_many :roles, :join_table => 'roles_permissions'
end


Is this correct? As when I try and access:

@user = User.find(params[:id])
@user.roles


I get the error:
undefined method 'roles' for #<User:0x007fc0176c6b08>


So it seems the relationships are not setup properly.

Answer

So it seems the relationships are not setup properly.

  1. You didn't add the association :)

    class User < ActiveRecord::Base
      has_and_belongs_to_many :roles, :join_table => 'users_roles'
    end
    
  2. join tables naming convention is alphabetical - it should be roles_users - if you change it, you won't have to specify the join_table option.