Rails-在进行多条件搜索时,如何使用nil值消除列?

时间:2017-09-27 15:11:19

标签: ruby-on-rails rails-activerecord

汽车有三个属性,"型号","位置","状态"。我想根据这三个条件搜索汽车。首先,我以为我可以使用

 Car.where(model: params[:car][:model], location: params[:car][:location], status: params[:car][:status])

但是,我不知道如何用nil值消除列。例如,如果我不输入表示params [:car] [:model] = nil的模型,它实际上会select * from car where model = null and status = ? and location = ? 但是,我想要的是select * from car where location= ? and status = ?。我怎么能做到这一点?

1 个答案:

答案 0 :(得分:1)

首先,您要切出所需的参数:

# `.fetch(:car, {})` prevents a nil error if the key is not present in the params.
params.fetch(:car, {}).permit(:location, :status, :model)
# or if `params[:car]` is required.
params.require(:car).permit(:location, :status, :model)

然后使用Hash#compact返回删除了nil值的新哈希:

irb(main):008:0> {"location"=>1, "status"=>nil, "model"=>"Ford Model T"}.compact
=> {"location"=>1, "model"=>"Ford Model T"}

共:

Car.where(params.fetch(:car, {}).slice(:location, :status, :model).compact)