我在category_controller.rb中有一个函数:
def index
@categories = Category.search(params[:search]).order name: :asc
if @categories
else
@categories = Category.all.order name: :asc
end
end
此代码有效。但是这会对模型进行两次查询。我怎么能只查询一次建模但保留我的代码的角色?
答案 0 :(得分:0)
可能的解决办法就是像这样做
def index
@categories = params[:search] ? Category.search(params[:search]).order(name: :asc) : Category.all.order(name: :asc)
end