Ruby on rails RubyonRails中过滤集合的最快方法

Ruby on rails RubyonRails中过滤集合的最快方法,ruby-on-rails,ruby-on-rails-4,Ruby On Rails,Ruby On Rails 4,我有一个模型,我正在尝试通过多个列进行过滤,其中一些可能不在过滤器中,我正在尝试加速此查询 以下是控制器索引方法的一个片段: def index @things = Thing.accessible_by(current_ability) if params.has_key?(:color) @things = @things.where(:color => params[:color]) end if params.has_key?(:we

我有一个模型,我正在尝试通过多个列进行过滤,其中一些可能不在过滤器中,我正在尝试加速此查询

以下是控制器索引方法的一个片段:

def index
    @things = Thing.accessible_by(current_ability)

    if params.has_key?(:color)
      @things = @things.where(:color => params[:color])
    end

    if params.has_key?(:weight)
      @things = @things.where(:weight => params[:weight])
    end

    if params.has_key?(:size)
      @things = @things.where(:size => params[:size])
    end

    @things = @things.order(:updated_at).page(params[:page]).per(params[:per_page])

end
我添加了以下索引:

add_index :things, :color
add_index :things, :weight
add_index :things, :size
试着找出最快的方法。还想将结果添加到由传入的参数串联而成的缓存中,这对添加有意义吗?不过,缓存只对后续过滤器有帮助,而不是初始过滤器


谢谢

这并不是为了加快查询速度,而是为了减少操作的规模

def index
    filtered_params = params.select{|x| [:color, :weight, :size].include? x}
    @things = Thing.accessible_by(current_ability)
               .where(filtered_params)
               .order(:updated_at)
               .page(params[:page])
               .per(params[:per_page])
end

你也可以考虑缓存视图,如果你的观点没有那么大的变化会有帮助。

查询需要多长时间,你认为它应该持续多长时间?解释输出是什么?查询350个事物需要约580毫秒。哦,有趣的是,看起来它在活动记录中只有40毫秒,但在呈现json时只有500毫秒:不要难过,当你比以前更好地理解你的问题时,它总是好的!令人高兴的是,关于加快Rails中JSON呈现的问题。只要确保你所接受的任何建议仍然适用于Rails4。