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)
確定域模型
。你如何在問題的'avaiable_domains'方法中實現這個? – rogal111 2012-07-18 14:21:42
沒有關聯':groups =>:網頁id域模型 – rogal111 2012-07-18 15:08:52
類似的東西)它將是一個單一的查詢,但我不確定它會執行更快 – 2012-07-18 15:36:35