在 rake 任务中启用 Rails SQL 缓存

Enable Rails SQL caching in rake task

我正在尝试在 rake 任务中启用 Rails SQL cache

rails documentation说:

If Rails encounters the same query again for that request, it will use the cached result

我想在 rake 任务中实现同样的效果。如果我多次执行相同的查询,我希望它使用前一个。

有什么方法可以使用该功能,还是我必须实施 Low-Level Caching

我相信你可以在一个块中启用缓存http://api.rubyonrails.org/classes/ActiveRecord/QueryCache/ClassMethods.html#method-i-cache

task your_rake_task: :environment do
  ActiveRecord::Base.connection.cache do
    # should cache queries inside the block
  end
end