如果它存在于 rails 中,则应用 where 条件

vis*_*tej 2 ruby activerecord ruby-on-rails rails-activerecord ruby-on-rails-5

在 rails activerecord 中有没有办法根据条件应用 where 条件?

例如:假设我想应用过滤器,如果它存在于输入参数中。假设@name 是必填字段,@salary 是可选字段。

@name = "test_name"
@salary = 2000
Run Code Online (Sandbox Code Playgroud)

我想做如下事情:

Employee.where(name: @name)
        .where(salary: @salary) if @salary.present?
Run Code Online (Sandbox Code Playgroud)

我知道要在多个 db 调用中进行,但我正在寻找一个选项来在单个 db 调用中实现这一点。

pot*_*hin 5

您只能通过存在的参数进行查询:

args = { name: @name, salary: @salary.presence }
Employee.where(args.compact)
Run Code Online (Sandbox Code Playgroud)


Ste*_*fan 5

您可以将第where一个的结果分配给变量并where有条件地调用第二个:

@employees = Employee.where(name: @name)
@employees = @employees.where(salary: @salary) if @salary.present?
Run Code Online (Sandbox Code Playgroud)

  • 它_看起来_就像在控制台中一样,因为控制台试图为您提供即时反馈,从而立即运行;但是Rails 直到需要某些查询的结果时才会执行查询。在控制台中,您可以运行`@employees = Employee.where(name: @name); nil` 并看到它实际上并没有在那里运行查询 (4认同)