2012-07-18 40 views
0

模型定義選擇從has_many_and_belongs_to_many對象:通過3個聯

class Article < ActiveRecord::Base 
    has_and_belongs_to_many :groups 
end 

class Group < ActiveRecord::Base 
    has_and_belongs_to_many :articles 
    has_many :domains, :inverse_of=>:group 
end 

class Domain < ActiveRecord::Base 
    belongs_to :group, :inverse_of=>:domains 
    has_many :pages, :inverse_of=>:domain 
end 

class Page < ActiveRecord::Base 
    belongs_to :domain, :inverse_of=>:pages 
    belongs_to :article, :inverse_of=>:pages 
end 

對於具體的Article我想選擇所有Domains沒有與該Article相關的任何Page(通過groups.domains相關)。

class Article < ActiveRecord::Base 
    has_and_belongs_to_many :groups 

    def avaiable_domains 
    groups.domains("where not exists page with article_id=#{id}")) ##???? 
    #I have code mentioned at the end of this question, but I don't want use SQL, just pure active query 
    end 
end 

是否有可能將它寫入純活動記錄查詢或Arel(在沒有SQL的情況下)?

現在我使用的是這樣的:

Domain.where(:group_id=>group_ids).where('NOT EXISTS(SELECT 1 FROM pages WHERE pages.domain_id=domains.id AND article_id=?)',id) 

回答

0
Domain.joins(:groups => :articles, :pages).where("pages.article_id <> :id AND articles.id = :id", id: article_id) 

在文章模型

def available_domains 
    Domain.available(id) 
    end 
+0

確定域模型

scope :available, ->(article_id){ joins(:groups => :articles,:pages). where("pages.article_id <> :id AND articles.id = :id", id: article_id) 

。你如何在問題的'avaiable_domains'方法中實現這個? – rogal111 2012-07-18 14:21:42

+0

沒有關聯':groups =>:網頁id域模型 – rogal111 2012-07-18 15:08:52

+0

類似的東西)它將是一個單一的查詢,但我不確定它會執行更快 – 2012-07-18 15:36:35