【问题标题】:Is there a way to cache the .all call?有没有办法缓存 .all 调用?
【发布时间】:2012-06-27 21:44:15
【问题描述】:

例如,我的索引控制器中有这个

@users = User.current

这是我的用户模型

 scope :current, :conditions => { :active => true }, :order => 'LOWER(first_name), LOWER(last_name) ASC'

这基本上是抓取所有记录并且我没有分页,因为我正在使用具有出色过滤器搜索功能的 jquery 数据表表......我想要实现的问题是尽可能缓存这些记录,除非有新用户...这并不经常发生

我读到了fresh_when,但不知道这里可以使用什么

更新

按照下面的答案后,我在日志中看不到缓存,我只看到了

  Company Load (0.4ms)  SELECT `companies`.* FROM `companies` INNER JOIN `positions` ON `companies`.`id` = `positions`.`company_id` WHERE `positions`.`user_id` = 551
  Company Load (0.4ms)  SELECT `companies`.* FROM `companies` INNER JOIN `positions` ON `companies`.`id` = `positions`.`company_id` WHERE `positions`.`user_id` = 93
  Company Load (0.4ms)  SELECT `companies`.* FROM `companies` INNER JOIN `positions` ON `companies`.`id` = `positions`.`company_id` WHERE `positions`.`user_id` = 668

【问题讨论】:

  • 您的数据库中有多少用户?
  • 您找到解决方案了吗?我有同样的问题? :(

标签: ruby-on-rails ruby ruby-on-rails-3 caching


【解决方案1】:
class User < ActiveRecord::Base
  after_save :clear_cache

  def self.current
    Rails.cache.fetch("current_users", expires_in: 1.hour) do
      User.where(active: true).order("LOWER(first_name), LOWER(last_name) ASC").all
    end
  end

private

  def clear_cache
    Rails.cache.delete("current_users")
  end

end

确保在 config/environments/*.rb 中启用缓存:

config.action_controller.perform_caching = true

这就是你想要的。在此处阅读更多信息:
http://robotmay.com/post/23161612605/everyone-should-be-using-low-level-caching?bda26d48
http://www.tmatthew.net/blog/rails-caching-example
http://api.rubyonrails.org/classes/ActiveSupport/Cache/Store.html#method-i-fetch

在缓存中存储模型时,您可能会遇到一个奇怪的问题,即在加载模型之前获取缓存时发生的问题。不用担心,这只会在开发中发生,并且有一个修复(application_controller.rb):

before_filter :load_models_if_dev
def load_models_if_dev
    if Rails.env == 'development'
        User; Post; Comment # whatever other classes that can get cached.
    end
end 

更新
注意User.where().order().all 中的.all。没有它,存储在缓存中的值只是一个 ActiveRecord 关系而不是实际结果。如果没有 .all ,查询仍然必须运行。感谢@Frederick Cheung 让我们注意到这一点。

【讨论】:

  • 您的解决方案看起来不错,但是当我查看日志时,我没有看到缓存,我每次都看到纯 sql...我会更新我的问题
  • 哦,是的...在开发中默认禁用缓存...见编辑
  • 一个保留 -- Rails 默认使用 FileStore 和 marshal/unmarshal,这可能比直接 SQL 慢(取决于本地磁盘),它也在 R3.2 中默认启用
  • 奇怪,因为我将 config.action_controller.perform_caching 更改为 true 并且仍然没有在开发日志中看到缓存....我重新启动并且仍然是直接 sql...如果那样的话,我正在使用 rails 3.2.6很重要
  • 如果你要使用 Rails.cache,你需要在你的作用域上调用 .all (或类似的),否则你只是在缓存作用域对象,而不是它的执行结果跨度>
猜你喜欢
  • 1970-01-01
  • 2017-03-21
  • 2016-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多