问题
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