在模型中调用 class 方法与在 rails 中调用控制器时的性能差异?

Performance difference when calling class methods in model vs controller in rails?

在我的 rails 应用程序中,我正在从数据库中获取一批数据,其中包含大约一百万条记录。我只是简单地结合一些分页逻辑调用以下查询,现在它运行良好。代码在我的模型中定义,如下所示:

def find_records(current_page, max_records, start_value, end_value)
   where(value_range: start_value..end_value)
        .offset((current_page - 1) * max_records).limit(max_records)
end

但是,在我之前的尝试中,我在我的模型中定义了以下代码:

def find_records(max_records, start_value, end_value)
   where(value_range: start_value..end_value)
end

然后我在控制器内部调用了 .offset.limit,如下所示:

def index
  current_page = params[:page]
  max_records = 3
  start_value = 4
  end_value = 8
  Model.find_records(start_value, end_value).offset((current_page - 1) * max_records).limit(max_records)
end

当我这样做时,我的记忆在第 3 或第 4 页完全消失,我的应用程序崩溃了。我不知道为什么在模型中调用 .limit.offset 解决了这个问题。

所以我的问题是,调用模型中的 class 方法而不是控制器如何提高代码执行性能?我的意思是这个查询显然与数据相关,所以无论如何在模型中调用它是有意义的,但我仍然想知道魔法背后的奇迹。

谢谢!

how does calling class methods in your model rather than the controller improve code execution performance?

不应该。您的查询 return 和 ActiveRecord::Relationoffsetlimit 都用于构建查询,因此在这两种情况下,您应该在日志中看到相同的查询。如有疑问,请检查您的 development.log

在您的模型中包含代码查询代码很有意义。控制器不应该知道所有这些细节。

关于分页,rails世界上有几个解决方案- Kaminari, will_paginate