我可以通过activerecord关系创建activerecord关联(使用祖先gem时)吗?

我在rails项目中使用ancestry gem来创建组的层次结构。 一个组可以属于父组,并且可以有许多子组。 每个组可以拥有许多属于某个组的用户。 该模型如下所示:

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

我希望能够为一个群体的后代获得所有用户,如下所示:

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

当然,这不起作用。

有什么建议?

在Group模型中定义这样的方法。

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

这将执行1次查询以获取subtree_ids和1次查询以获取用户,结果已经是不同的用户设置。

可能你应该定义方法,它返回所有后代的用户。 所以你的模型看起来像这样:

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