Reputation: 6317
I currently have the following in my controller:
@items = Item.scoped
@items = @items.where('price >= ?', params[:price_min]) if params[:price_min]
@items = @items.where('price <= ?', params[:price_max]) if params[:price_max]
@items = @items.where(:size => params[:size]) if params[:size]
@items = @items.where(:colour => params[:colour]) if params[:colour]
# ...
@items = @items.paginate(:page => params[:page], :per_page => 10)
Is this the right place for this code, or should it really belong in my model with a single method call in the controller? i.e.
@items = Item.apply_filters(params)
I am trying to stick to convention as much as possible.
Many thanks.
Upvotes: 1
Views: 169
Reputation: 4432
Also, if your items are always going to be scoped, you can make that the default_scope
. In your model:
default_scope order("item_number"), where('price >= ?', 100)
(I'm not totally sure I got all of that syntax correct, but it's something like that.)
named_scope
might also help you out.
Upvotes: 1
Reputation: 51697
You are correct that this all belongs in your model. This is very similar to someone's code that I reviewed the other day. The MetaWhere gem might be a good fit for your project as well.
Upvotes: 2