2011-02-02 9 views
0

を通じて私は、Active Recordのモデルのセットを持って、このようなセットアップ:、どのように私は2つにhas_manyの間でマージされた関係を作成することができます。関係

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は次のようになります。それはあまりにも、名前の範囲または関係だけではなく、ファインダー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 

答えて

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:グループとグループhas_many account_groupsを要求する