【问题标题】:ActiveRecord query based on multiple objects via has_many relationship通过 has_many 关系基于多个对象的 ActiveRecord 查询
【发布时间】:2014-09-25 22:10:41
【问题描述】:

我有一个Product 类,它是has_many GenderConnection 类实例。我想查询以查找同时具有end_aend_b 的产品。当前的类方法有两个注意事项:

  • 如果搜索end_aend_b 相同的位置,则无法正确返回。相反,应该搜索 product 是否有 2 个实例,而不仅仅是一个对象。
  • 当我想要 ActiveRecord_Relation 时返回 Array

类方法.query如下,欢迎反馈或意见。

class Product < ActiveRecord::Base

  has_many   :connections, dependent: :destroy, as: :connectionable
  has_many   :genders,     through:   :connections

  def self.query(end_a, end_b)
    search_base = active.joins(:connections)
    end_a_search = search_base.where(connections: { gender_id: end_a  } )

    end_a_search & search_base.where(connections: { gender_id: end_b  } )
  end
end

ps:一旦解决这个问题,很可能会将其移至Product 的范围内

【问题讨论】:

  • 什么是连接?加入模型?
  • @BroiSatse 修复了上述问题,但Genders 属于ProductConnections
  • scope :some_query , -&gt;(end_a, end_b) Product.joins(:connections).where("connections.gender_id = ? OR connections.gender_id = ?", end_a, end_b)
  • @bjhaid 我认为这行不通,因为它会返回仅与end_aend_b 有关系的产品实例。我需要产品与end_aend_b 都有关系。

标签: sql ruby-on-rails ruby activerecord ruby-on-rails-4


【解决方案1】:
class Product < ActiveRecord::Base
  has_many :connections, dependent: :destroy, as: :connectionable
  has_many :genders, through: :connections

  scope :with_genders, -> (end_a, end_b) {
    relation = joins('INNER JOIN connections c1 ON c1.connectionable_id = products.id AND c1.connectionable_type = \'Product\'')
      .joins('INNER JOIN connections c2 ON c1.connectionable_id = c2.connectionable_id AND c2.connectionable_type = \'Product\'')
      .where(c1: {gender_id: end_a}, c2: {gender_id: end_b})
      .group('products.id')
    end_a == end_b ? relation.having('COUNT(products.id) > 1') : relation
  }
end

【讨论】:

  • 我很抱歉,但connections 是多态的,所以当我尝试上述方法甚至用connectionable_id 替换product_id 时,如果搜索end_aend_b 的位置,它仍然无法正确返回一样的。
  • 查看更新后的回复。此外,将来尝试在您的问题中提供所有必要的信息 - 通过这样做,您可以节省那些帮助您的人的时间。
  • 我很抱歉之前没有提到多态模型。但我实现了您更新的范围,并收到错误PG::UndefinedColumn: ERROR: column "Product" does not exist LINE 1。感谢您迄今为止的所有帮助。
  • 感谢更新,现在代码正在运行,但未涵盖我在初始帖子中提到的警告:“如果搜索 end_aend_b 相同的位置,则无法正确返回。而是应该搜索产品是否有 2 个实例,而不仅仅是一个对象。”知道如何解决这个问题吗?
  • 对不起,我可能没有仔细阅读描述。看看最后的更新,是你需要的吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-14
  • 2011-10-09
  • 1970-01-01
  • 1970-01-01
  • 2020-10-19
相关资源
最近更新 更多