I am trying to create a scope string for a search form. Can I build something like this with scopes:
scopestring = Product.all
if params[:price].include?
scopestring = scopestring + '.free'
if params[:location].include?
# same for location
end
Obviously I can’t do that, but is there a way to do something similar. Any suggestions? Not a fan of 9 condition IF or case statements to handle various filters on the search page.
If I am going totally in a wrong direction here, what is the best way to handle long conditional statements in Rails? I would prefer staying away from gems.
First,
Product.allisn’t a scope, it actually does the search. What you want isProduct.scoped. The scope returned is an object, not a string. Assuming that:freeis a scope:You can simplify it a bit more by refactoring into the model:
and then in your controller: