Rails 3 filtering multiple parameters using scopes

An attempt to make a basic filter in rails 3 using url parameters. I would like to have a white list of parameters that can be filtered, and return all the elements that match. I created several areas (many more others):

# in the model: scope :budget_min, lambda {|min| where("budget > ?", min)} scope :budget_max, lambda {|max| where("budget < ?", max)} 

... but what is the best way to use some, none or all of these areas based on real params[] ? I got this far, but this does not apply to a few options. Search for the type of operation "chain, if present".

 @jobs = Job.all @jobs = Job.budget_min(params[:budget_min]) if params[:budget_min] 
+4
source share
3 answers

I think you are close. Something like this will not apply to multiple parameters?

 query = Job.scoped query = query.budget_min(params[:budget_min]) if params[:budget_min] query = query.budget_max(params[:budget_max]) if params[:budget_max] @jobs = query.all 
+6
source

As a rule, I would prefer the solutions made by hand, but for this problem the code base could become a mess very quickly. So I would like to get a gem like meta_search .

+1
source

One way is to put your legend in scope:

 scope :budget_max, lambda { |max| where("budget < ?", max) unless max.nil? } 

This will still become rather cumbersome since you are done:

 Job.budget_min(params[:budget_min]).budget_max(params[:budget_max]) ... 

A slightly different approach will use something like the following in your model: (based on the code here :

 class << self def search(q) whitelisted_params = { :budget_max => "budget > ?", :budget_min => "budget < ?" } whitelisted_params.keys.inject(scoped) do |combined_scope, param| if q[param].nil? combined_scope else combined_scope.where(whitelisted_params[param], q[param]) end end end end 

Then you can use this method as follows, and it should use whitelists if they are present in the parameters:

 MyModel.search(params) 
+1
source

Source: https://habr.com/ru/post/1383682/


All Articles