我正在列出产品,我希望能够将哈希值作为我的 where 子句传递,这样我就可以执行以下操作:
filter = {}
filter[:category_id] = @category.id
filter[:is_active] = true
@products = Products.where(filter)
是否有可能以某种方式做到这一点?
我还需要在我的 where 子句中添加类似这样的内容:
WHERE price > 100
如何将其添加到过滤器?
我想这样做的原因是因为在 UI 中我将有一组可选的过滤器,所以我将在我的 Controller 中使用 if 子句来设置每个过滤器。
最佳答案
您可以将散列传递给 where
,就像您所做的那样:
filter = {
category_id: @category_id,
is_active: true
}
@products = Product.where(filter)
使用哈希仅适用于相等(例如 category_id = 123
),因此您不能在其中放置类似 price > 100
的内容。要添加该条件,只需将另一个 where
添加到链中:
@product = Product.where(filter).where('price > 100')
或者...
@product = Product.where(filter)
if params[:min_price]
@product = @product.where('price > ?', min_price)
end
关于ruby-on-rails - 如何为我的 where 子句传递散列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31167679/