如何使用包含activerecord关联?

时间:2012-06-22 00:15:52

标签: ruby-on-rails ruby-on-rails-3 activerecord

给出两个模型:

User
  has_many :group_members
  has_many :groups, :through => :group_members

GroupMember
  belongs_to :group
  belongs_to :user

Group
  has_many :group_members
  has_many :users, :through => :group_members
  has_many :group_invites

GroupInvite
  belongs_to :user

感谢Rails,我可以轻松地获得所有用户组:

groups = current_user.groups

然后我获取这个组列表并迭代创建一个JSON对象,如下所示:

groups.each do |group|
  ....
  group.group_members.count
  group.invites.first_code
等等。问题是这会导致大量查询,因为我还没有找到一种方法来使用includes(:)来查询所有group_members并邀请所有具有一个查询的组与每个每个循环的查询。关于如何使用的任何建议包括如下:

current_user.groups.includes(:group_members, :invites) ?

1 个答案:

答案 0 :(得分:2)

试试这个:

GroupMember
  belongs_to :group
  belongs_to :user

Group
  has_many :group_members
  has_many :users, :through => :group_members
  has_many :invites, :
  has_many :invitees, :through => :invites, :source => :user

Invite
  belongs_to :group
  belongs_to :user

现在你可以:

current_user.groups.includes(:invitees)