从has_many_and_belongs_to_many到3个关联中选择对象

时间:2012-07-18 12:46:46

标签: mysql ruby-on-rails activerecord

模型定义:

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关联),而PageArticle没有关联。

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 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)

1 个答案:

答案 0 :(得分:0)

Domain.joins(:groups => :articles, :pages).where("pages.article_id <> :id AND articles.id = :id", id: article_id)
域模型中的

   scope :available, ->(article_id){ joins(:groups => :articles,:pages).
          where("pages.article_id <> :id AND articles.id = :id", id: article_id)
文章模型中的

  def available_domains
    Domain.available(id)
  end