【发布时间】:2016-05-13 12:43:39
【问题描述】:
我的产品模型设置如下:
class Product < ActiveRecord::Base
has_many :product_atts, :dependent => :destroy
has_many :atts, :through => :product_atts
has_many :variants, :class_name => "Product", :foreign_key => "parent_id", :dependent => :destroy
end
我想搜索与多个属性关联的产品。
我想也许这会起作用:
Product.joins(:product_atts).where(parent_id: params[:product_id]).where(product_atts: {att_id: [5,7]})
但这似乎并不符合我的要求。这在 ID 或 ID 处执行。
所以我尝试了以下方法:
Product.joins(:product_atts).where(parent_id: 3).where(product_atts: {att_id: 5}).where(product_atts: {att_id: 7})
但这也不起作用,它返回 0 个结果。
所以我的问题是如何通过传入相同模型类型的多个连接模型的属性来查找模型?
解决方案:
att_ids = params[:att_ids] #This is an array of attribute ids
product = Product.find(params[:product_id]) #This is the parent product
scope = att_ids.reduce(product.variants) do |relation, att_id|
relation.where('EXISTS (SELECT 1 FROM product_atts WHERE product_id=products.id AND att_id=?)', att_id)
end
product_variant = scope.first
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-3 postgresql activerecord