如果 rails 中存在则应用 where 条件
Apply where condition if it exists in rails
rails activerecord 中是否有一种方法可以根据条件应用 where 条件?
例如:
假设我想应用输入参数中存在的过滤器。
假设@name 是必填字段,@salary 是可选字段。
@name = "test_name"
@salary = 2000
我想做如下的事情:
Employee.where(name: @name)
.where(salary: @salary) if @salary.present?
我知道在多个数据库调用中实现它,但我正在寻找一个选项来在单个数据库调用中实现它。
您只能通过存在的参数进行查询:
args = { name: @name, salary: @salary.presence }
Employee.where(args.compact)
您可以将第一个 where
的结果分配给一个变量并有条件地调用第二个 where
:
@employees = Employee.where(name: @name)
@employees = @employees.where(salary: @salary) if @salary.present?
您可以将所有可能的参数添加到一个散列中,并删除 nil
和 Hash#compact
:
的那些
Employee.where({ name: @name, salary: @salary }.compact)
rails activerecord 中是否有一种方法可以根据条件应用 where 条件?
例如: 假设我想应用输入参数中存在的过滤器。 假设@name 是必填字段,@salary 是可选字段。
@name = "test_name"
@salary = 2000
我想做如下的事情:
Employee.where(name: @name)
.where(salary: @salary) if @salary.present?
我知道在多个数据库调用中实现它,但我正在寻找一个选项来在单个数据库调用中实现它。
您只能通过存在的参数进行查询:
args = { name: @name, salary: @salary.presence }
Employee.where(args.compact)
您可以将第一个 where
的结果分配给一个变量并有条件地调用第二个 where
:
@employees = Employee.where(name: @name)
@employees = @employees.where(salary: @salary) if @salary.present?
您可以将所有可能的参数添加到一个散列中,并删除 nil
和 Hash#compact
:
Employee.where({ name: @name, salary: @salary }.compact)