我可以通过创建一个ActiveRecord关系的ActiveRecord的关联(使用祖先宝石时)? [英] Can I create an activerecord association through an activerecord relation (when using the ancestry gem)?

查看:146
本文介绍了我可以通过创建一个ActiveRecord关系的ActiveRecord的关联(使用祖先宝石时)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是祖先宝石在我的Rails项目创建一个层次的基团。一组可以属于一个父组,并且可以具有许多儿童组。每个组可以有谁属​​于一个组许多用户。该模型是这样的:

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.

有什么建议?

推荐答案

在您的集团模式定义这样的方法。

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

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

This will perform 1 query to fetch subtree_ids and 1 query to fetch users, and the result is already distinct users set.

这篇关于我可以通过创建一个ActiveRecord关系的ActiveRecord的关联(使用祖先宝石时)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆