Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 multiple parameter filtering using scopes

Trying to do a basic filter in rails 3 using the url params. I'd like to have a white list of params that can be filtered by, and return all the items that match. I've set up some scopes (with many more to come):

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

...but what's the best way to use some, none, or all of these scopes based on the present params[]? I've gotten this far, but it doesn't extend to multiple options. Looking for a sort of "chain if present" type operation.

@jobs = Job.all
@jobs = Job.budget_min(params[:budget_min]) if params[:budget_min]
like image 356
brittohalloran Avatar asked Feb 22 '23 06:02

brittohalloran


1 Answers

I think you are close. Something like this won't extend to multiple options?

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
like image 164
maxenglander Avatar answered Mar 08 '23 13:03

maxenglander