【问题标题】:Select objects from has_many_and_belongs_to_many through 3 associations通过 3 个关联从 has_many_and_belongs_to_many 中选择对象
【发布时间】:2012-07-18 12:46:45
【问题描述】:

模型定义:

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 关联)而没有与Article 关联的任何Page

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)

【问题讨论】:

    标签: mysql ruby-on-rails activerecord


    【解决方案1】:
    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
    

    【讨论】:

    • 好的。您如何在问题的avaiable_domains 方法中实现这一点?
    • 没有关联:groups =&gt; :pagesid域模型
    • 类似的东西)这将是一个单一的查询,但我不确定它会执行得更快
    猜你喜欢
    • 2016-05-29
    • 2023-01-30
    • 1970-01-01
    • 2015-07-21
    • 1970-01-01
    • 2017-03-15
    • 1970-01-01
    • 2020-08-14
    • 1970-01-01
    相关资源
    最近更新 更多