我正在看一个Ryan Bates的屏幕演员(虽然是较旧的),他正在实现一些简单的搜索功能。我正在寻求更好的理解,因为我希望在我的应用程序中实现稍微复杂一些的东西。
在他的控制器中他有
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
我这样做是否有不利之处,或者我应该在模型中创建查询?
由于
答案 0 :(得分:1)
这应该有用。
def rehomed
@animals = Animal.search(params).paginate(:page => params[:new_page], :per_page => 6)
end
class Animal
def self.search(params)
animals = Animal.joins(:user)
animals = animals.where(animal_type: params[:animal_type]) if params[:animal_type].present?
animals = animals.where(rehomed: params[:rehomed]) if params[:rehomed].present?
animals = animals.where(users: {town: params[:animal_town]}) if params[:animal_town].present?
animals
end
end