sql - Rails 3 有多个参数

标签 sql ruby-on-rails ruby-on-rails-3 where-clause parameters

我需要构建一个带有 2 个传入参数的动态 SQL 队列。当两个参数都被定义时,这很容易。

MyClass.where(:column1 => param[:first], :column2 => params[:second])

但是,例如 param[:first] = 0 我想选择此列的所有(非空)字段(因此,当两个参数都 = 0 时,它将等于 从表名中选择*)。尝试过这个语法:

MyClass.where(:column1 => param[:first], :column2 => !nil)

但它给了我错误的输出。有什么建议如何优雅地解决这个问题吗?

最佳答案

您可以在 where: 中使用 ?: 运算符:

MyClass.where(params[:first] ? {:column1 => params[:first]} : "column1 IS NOT NULL")
       .where(params[:second] ? {:column2 => params[:second]} : "column2 IS NOT NULL")

关于sql - Rails 3 有多个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11296182/

相关文章:

sql - 优化查询

ruby-on-rails - 生产和开发之间奇怪的时间不一致

mysql - sql 按另一个值排序和限制

php - 如何在 CakePHP 中执行自定义查询

mysql - 在具有不同类型交易的sql连接交易表中

ruby-on-rails - 我没有路线匹配 { :controller= >"refinery/refinery/admin/dashboard"} error

ruby-on-rails - 为什么在 has_many :through trigger callbacks on the join model on deletion of the association? 上没有 collection=objects

mysql - 来自现有数据库的 seed_fu

ruby-on-rails - 无法为 ActionMailer::Base 找到 Rails 3 "The action ' 方法'

ruby-on-rails - rails : Storing Post ID in Comment Table in DB