My User model looks like:
User
habtm :Roles
Role
habtm :Users
RoleExtension
belongs_to :Role
mysql tables:
user = User.find(1) RoleExtension.find(:all, :conditions => ["role_id IN (?)", user.role_ids])
Otherwise you can use nested joins.
@user.role_extensions.where(:joins => :roles)
Normally you'd use a has_many, :through association, but that doesn't apply to has_and_belongs_to_many
relations.
So, instead, in your User model:
def role_extensions
return roles.inject([]) do |array, role|
role.role_extensions do |re|
array.include?(re) ? array << re : array
end
end
end
Then my_user.role_extensions
should return an array of all role extensions belonging to all the user's roles.
Note: I haven't tested this, but it should work
UPDATE: I like this better
def role_extensions
return roles.inject([]) { |array, role| array << role.role_extensions }.flatten!.uniq
end
Try this -
# Fetch user object
user = User.first
# If you want roles of that user try this
roles = user.roles
# You can map all the role extensions of that user by
role_extensions = user.roles.map(&:role_extensions).uniq
Be aware that this will be extremely slow for large number of roles. In that case better write your own query method. Something like
role_extensions = RoleExtension.where("role_id in (?)", user.role_ids).all