在rails中,如何在两个has_many:through relationship之间创建合并关系

时间:2011-02-02 21:37:40

标签: ruby-on-rails activerecord has-many-through

我有一组Active Record模型,设置如下:

Account
  has_many :account_groups
  has_many :groups, :through => :account_groups

Posts
  has_many :post_groups
  has_many :groups, :through => :post_groups

这是一个安全配置,我需要能够查询属于帐户有权访问的组的帖子....所以,我希望能够说:

@account.posts

获取对属于与帐户有权访问的群组重叠的群组的帖子的过滤查询....但我似乎无法找出正确的语法。

帮助。

为了澄清,我想要生成的SQL看起来像:

SELECT DISTINCT posts.* FROM accounts
    JOIN account_groups ON account_groups.account_id = accounts.id
    JOIN groups ON groups.id = account_groups.group_id
    JOIN post_groups ON post_groups.group_id = groups.id
    JOIN posts ON posts.id = post_groups.post_id
    WHERE accounts.id = 2

我真的希望它是一个命名的范围或关系,而不仅仅是finder sql。

1 个答案:

答案 0 :(得分:1)

我能得到的最接近:

class Account < ActiveRecord::Base
  def posts
    Post.includes(:post_groups => [:group => [:account_groups => :account]]).where('account_groups.account_id = ?',1)
  end
end

您可以将其提取到范围,而不是:

class Post < ActiveRecord::Base
  has_many :post_groups
  has_many :groups, :through => :post_groups

  scope :for_account, lambda {|account| joins(:post_groups => [:group => [:account_groups => :account]]).where('account_groups.account_id = ?',account.id)}
end

两者都产生:

SELECT "posts".* FROM "posts" INNER JOIN "post_groups" ON "post_groups"."post_id" = "posts"."id" INNER JOIN "groups" ON "groups"."id" = "post_groups"."group_id" INNER JOIN "account_groups" ON "account_groups"."group_id" = "groups"."id" INNER JOIN "accounts" ON "accounts"."id" = "account_groups"."account_id" WHERE (account_groups.account_id = 1)

这两个......要求PostGroup belongs_to:group and group has_many account_groups