ruby-on-rails - 如何为我的 where 子句传递散列?

标签 ruby-on-rails

我正在列出产品,我希望能够将哈希值作为我的 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/

相关文章:

javascript - 每 15 秒向 Rails 方法发出一次 JS 请求有多高效

mysql - 事件记录(mysql db)文本字段中的字符数是否有限制

javascript - Rails Assets 管道 : Return digest version when non-digest requested

ruby-on-rails - rails 4 中不允许的参数

ruby-on-rails - Rails 开发模式渲染 View 非常慢

ruby-on-rails - 匹配和分离 Rails 序列化数组

ruby-on-rails - 如何删除 Rails 模型上 validates_presence_of 中的字段名称

ruby-on-rails - 当 find 涉及单个属性但 create 涉及多个属性时实现 find_or_create_by

ruby-on-rails - 是否可以通过.send 设置属性值?

ruby-on-rails - Rails Assets 缓存未清除 - Docker、Rails、Nginx