Model.where() 带有多个参数,检查它们是否存在于 rails 中
Model.where() with multiple params with check if they are present in rails
我是 Rails 的新手。我开始研究 POC。
我的控制器代码如下:
@xyz = if params[:id].present?
if params[:mobile_number].present?
Seeker.where("id = ? and mobile_number = ?" , params[:id], params[:mobile_number])
else
Seeker.where("id = ?", params[:id])
end
elsif params[:seekerid].present?
Seeker.where("mobile_number = ?" , params[:mobile_number])
else
Seeker.where(nil);
end
但我认为这不是一个好方法。考虑一下如果我有很多参数然后放置 present?
条件然后形成查询将变得复杂。或者我可以单独形成一个查询,然后将它作为实例变量放入 where 条件中。
最好的方法是什么?
您可以在存在每个参数时递增地添加 where
语句:
@xyz = Seeker.scoped
@xyz = @xyz.where(id: params[:id]) if params[:id].present?
@xyz = @zyx.where(mobile_number: params[:mobile_number]) if params[:mobile_number].present?
更简洁的方法可能是将该逻辑移动到某个范围或 Seeker 模型中的 class 方法。
嗨I am new to Rails
如果你正在使用搜索小项目,小数据库,你可以使用Ruby的scope,看看arieljuod的回答。但是如果你想让你的搜索功能更快,更深入,......你可以找到一些宝石:
Ruby 在 Rails 上还有许多其他令人惊奇的方式。
编码愉快!!!
如果你想根据即将到来的每个参数查找记录并具有价值,那么使用它的最佳方法是
params = {id: nil, mobile_number: "98XXXXXX12" }
Seeker.where(params.compact)
compact 将从参数中删除 nil 值并直接使用现有参数查找。
注意: 它只会删除 nil 值而不是 " " blank String
我是 Rails 的新手。我开始研究 POC。
我的控制器代码如下:
@xyz = if params[:id].present?
if params[:mobile_number].present?
Seeker.where("id = ? and mobile_number = ?" , params[:id], params[:mobile_number])
else
Seeker.where("id = ?", params[:id])
end
elsif params[:seekerid].present?
Seeker.where("mobile_number = ?" , params[:mobile_number])
else
Seeker.where(nil);
end
但我认为这不是一个好方法。考虑一下如果我有很多参数然后放置 present?
条件然后形成查询将变得复杂。或者我可以单独形成一个查询,然后将它作为实例变量放入 where 条件中。
最好的方法是什么?
您可以在存在每个参数时递增地添加 where
语句:
@xyz = Seeker.scoped
@xyz = @xyz.where(id: params[:id]) if params[:id].present?
@xyz = @zyx.where(mobile_number: params[:mobile_number]) if params[:mobile_number].present?
更简洁的方法可能是将该逻辑移动到某个范围或 Seeker 模型中的 class 方法。
嗨I am new to Rails
如果你正在使用搜索小项目,小数据库,你可以使用Ruby的scope,看看arieljuod的回答。但是如果你想让你的搜索功能更快,更深入,......你可以找到一些宝石:
Ruby 在 Rails 上还有许多其他令人惊奇的方式。
编码愉快!!!
如果你想根据即将到来的每个参数查找记录并具有价值,那么使用它的最佳方法是
params = {id: nil, mobile_number: "98XXXXXX12" }
Seeker.where(params.compact)
compact 将从参数中删除 nil 值并直接使用现有参数查找。
注意: 它只会删除 nil 值而不是 " " blank String