Can I create an activerecord association through an activerecord relation (when using a family tree)?

I use the pedigree in my rails project to create a group hierarchy. A group may belong to a parent group and may have many groups of children. Each group can have many users who belong to the group. The model is as follows:

class Group < ActiveRecord::Base has_ancestry has_many :users end 

I would like all users to be available to the descendants of the group, something like this:

 class Group < ActiveRecord::Base has_ancestry has_many :users has_many :descendants_users, through: :descendants end 

which of course does not work.

Any suggestions?

+4
source share
2 answers

Define a method similar to this in the group model.

 def descendants_users User.joins(:groups).where(:group_id => self.subtree_ids) # Use descendant ids if you dont't want 'self' users end 

This will execute query 1 to retrieve the subtree data and query 1 to get users, and the result is already different from the set of users.

+2
source

Perhaps you just need to define a method that returns all descendant users. So your model might look like this:

  class Group < ActiveRecord::Base has_ancestry has_many :users def descendants_users self.subtree.map(&:users).flatten.compact.uniq end end 
+1
source

Source: https://habr.com/ru/post/1442352/


All Articles