我有一个Product
类has_many
Gender
到Connection
类实例。我想查询以查找同时存在end_a
和end_b
的商品。当前的类方法有两个注意事项:
end_a
和end_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
答案 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