在轨道上的红宝石模型上使用一次

时间:2017-05-27 05:15:09

标签: ruby-on-rails

我在category_controller.rb中有一个函数:

def index
 @categories = Category.search(params[:search]).order name: :asc
 if @categories
 else
  @categories = Category.all.order name: :asc
 end
end

此代码有效。但是这会对模型进行两次查询。我怎么能只查询一次建模但保留我的代码的角色?

1 个答案:

答案 0 :(得分:0)

可能的解决办法就是像这样做

def index
 @categories = params[:search] ? Category.search(params[:search]).order(name: :asc) : Category.all.order(name: :asc)
end