ActiveRecord通过has_many关系基于多个对象进行查询

时间:2014-09-25 22:10:41

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

我有一个Producthas_many GenderConnection类实例。我想查询以查找同时存在end_aend_b的商品。当前的类方法有两个注意事项:

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

下面是课程方法.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

的范围内

1 个答案:

答案 0 :(得分: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