型号定义:
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
(通过关联groups.domains
)而不Page
与该关联Article
。
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
是否可以在纯 Active Record Query 或 Arel 中编写它(在 where 方法中没有 SQL)?
现在我正在使用这个:
Domain.where(:group_id=>group_ids).where('NOT EXISTS(SELECT 1 FROM pages WHERE pages.domain_id=domains.id AND article_id=?)',id)