Rails Find when some params will be blank

萝らか妹 提交于 2019-12-11 01:38:21

问题


I have a search form with two fields: x, y

When the search is performed it will look for records that match all conditions. However any of the two conditions can be set to 'All' by leaving it blank.

What should I set params[:x] and params[:y] to if they are set to all.

params[:x] = ? unless params[:x]
params[:y] = ? unless params[:y]

users = User.where(["x = ? AND y = ?", params[:x], params[:y]])

回答1:


I would suggest building up your conditions using a hash:

conditions = {}
conditions[:x] = params[:x] unless params[:x].blank?
conditions[:y] = params[:y] unless params[:y].blank?

users = User.find(:all, :conditions => conditions)



回答2:


You need to chain your conditions instead of trying to construct a scope that's so specific. You can use a sliding scope technique:

scope = User

if (params[:x].present?)
  scope = scope.where(:x => params[:x])
end

if (params[:y].present?)
  scope = scope.where(:y => params[:y])
end

users = scope.all

This way you can conditionally engage restrictions based on parameters that may be present.



来源:https://stackoverflow.com/questions/4234086/rails-find-when-some-params-will-be-blank

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!