Can I add an association based on another association?

My user model is as follows:

User habtm :Roles Role habtm :Users RoleExtension belongs_to :Role 

mysql tables:

 users id .. roles id .. roles_users user_id role_id role_extensions id role_id feature_id .. .. 

Now everything is working fine.

Now I want the User model to have a RoleExtensions set based on the habtm Roles collection.

Example:

 user = User.find(1) user.Roles (returns roles with id of 1,2,3) 

So I want:

 user.RoleExtensions 

to return all role extensions that have role_id in (1,2,3)

+1
ruby-on-rails
source share
4 answers

Usually you use the has_many, :through has_and_belongs_to_many has_many, :through association, but this does not apply to the has_and_belongs_to_many relationships.

So, 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 user roles.

Note. I have not tested this, but it should work

UPDATE : I like it better

 def role_extensions return roles.inject([]) { |array, role| array << role.role_extensions }.flatten!.uniq end 
+1
source share
 user = User.find (1)
 RoleExtension.find (: all,: conditions => ["role_id IN (?)", User.role_ids])

Otherwise, you can use nested connections.

0
source share

Try it -

 # 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 

Remember that this will be extremely slow for a lot of roles. In this case, it is better to write your own request method. Something like

 role_extensions = RoleExtension.where("role_id in (?)", user.role_ids).all 
0
source share
 @user.role_extensions.where(:joins => :roles) 
0
source share

All Articles