Can I create an activerecord association through an activerecord relation (when using the ancestry gem)?

心已入冬 提交于 2019-12-10 17:17:14

问题


I am using the ancestry gem in my rails project to create a hierarchy of groups. A group can belong to a parent group and can have many children groups. Each group can have many users who belong to a group. The model looks like this:

class Group < ActiveRecord::Base
  has_ancestry

  has_many :users
end

I would love to be able to get all users for the descendants of a group, something like this:

class Group < ActiveRecord::Base
  has_ancestry

  has_many :users
  has_many :descendants_users, through: :descendants
end

which, of course, doesn't work.

Any suggestions?


回答1:


Define a method like this in your 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 perform 1 query to fetch subtree_ids and 1 query to fetch users, and the result is already distinct users set.




回答2:


May be you just should to define method, that returns all of descendants' users. So your model could look like this:

  class Group < ActiveRecord::Base
    has_ancestry

    has_many :users

    def descendants_users
      self.subtree.map(&:users).flatten.compact.uniq
    end
  end


来源:https://stackoverflow.com/questions/13090848/can-i-create-an-activerecord-association-through-an-activerecord-relation-when

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!