2011-02-03 60 views
1

我現在有在我的控制器如下:Rails:這段代碼屬於哪裏?

@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) 

這是此代碼正確的地方,還是應該真正屬於我的模型與控制器一個方法調用?即

@items = Item.apply_filters(params) 

我試圖儘可能地堅持約定。

非常感謝。

回答

1

另外,如果您的項目總是會先限定,你可以說:default_scope。在你的模型:

default_scope order("item_number"), where('price >= ?', 100) 

(我不能完全肯定我得到了所有的語法正確的,但它是類似的東西。)

named_scope也可以幫助你。

+0

+1的default_scope信息。謝謝。 – gjb 2011-02-03 15:40:50