大型模型存在参数时的Rails过滤器 [英] Rails filter when param is present for large model

查看:67
本文介绍了大型模型存在参数时的Rails过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此博客文章说明了如何根据此代码中存在的参数进行过滤。

This blog post explains how to filter based on the parameters that are present with this code.

def index
  @products = Product.where(nil) # creates an anonymous scope
  @products = @products.status(params[:status]) if params[:status].present?
  @products = @products.location(params[:location]) if params[:location].present?
  @products = @products.starts_with(params[:starts_with]) if params[:starts_with].present?
end

Product.where(nil)该解决方案的一部分是有问题的,因为如果模型很大,它将把所有内容加载到内存中并导致服务器崩溃。

The Product.where(nil) part of the solution is problematic because it will load everything into memory and cause your server to crash if the model is big.

其中一个博客评论者说:使用 Product.none 代替 Product.where(nil)更好吗?但我无法使用该解决方案。

One of the blog post commenters said "Isn't it better to use Product.none instead of Product.where(nil)?" but I couldn't get that solution to work.

此Stackoverflow答案通过 joins 方法访问 ActiveRecord :: Relation 对象。我没有加入,所以此解决方案对我不起作用。

This Stackoverflow answer accesses the ActiveRecord::Relation object via the joins method. I'm not doing a join, so this solution won't work for me.

请告诉我是否有更好的方法或完全不同的方法我应该解决这个问题。谢谢!

Let me know if there is a better way to do this or a completely different way I should approach this problem. Thanks!

推荐答案

为什么不只使用 .all 并合并

def filter_by_params
  params.slice(:status, :location, :starts_with)
    .compact # removes keys with nil values
    # iterates though the hash and returns a scope
    .each_with_object(Product.all) do |(key, value), scope|
      scope.merge(Product.send(key, value))
    end
end

这篇关于大型模型存在参数时的Rails过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆