0

型号定义:

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

1 回答 1

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
于 2012-07-18T14:00:23.203 回答