0
我在看一個瑞安貝茨屏幕演員(雖然是一個較老的),他正在實現一些簡單的搜索功能。我只是希望得到更好的理解,因爲我正在尋找在我的應用程序中實現稍微複雜一些的東西。通過控制器或模型的搜索查詢
在他的控制,他有
def index
@products = Product.search(params[:search]).paginate(:per_page => 5, :page => params[:page])
end
然後
def self.search(search)
if search
find(:all, :conditions => ['name LIKE ?', "%#{search}%"])
else
find(:all)
end
end
他的搜索方法的類方法(模型)是在他的模型,其中作爲即時通訊我的應用我建立我的搜索查詢在我的控制器
class PublicController < ApplicationController
def rehomed
conditions = {}
conditions.merge!(animal_type: params[:animal_type]) if params[:animal_type].present?
conditions.merge!(rehomed: params[:rehomed]) if params[:rehomed].present?
conditions.merge!(users: {town: params[:animal_town]}) if params[:animal_town].present?
@animals = Animal.joins(:user).where(conditions).paginate(:page => params[:new_page], :per_page => 6)
end
end
有什麼缺點我這樣做,或者我應該要創建我的q uery在我的模型中?
謝謝
我會在模型中做到這一點,它看起來更清潔。如果我可以避免的話,不是在控制器中擁有大量邏輯的粉絲。 – 2014-11-06 09:21:49
好的下一個問題,那麼我怎麼可以轉換我在模型中使用?如果你能提供幫助,將是一個很大的幫助 – Richlewis 2014-11-06 09:29:47