例如我在我的索引 Controller 中有这个
@users = User.current
这是我的用户模型
scope :current, :conditions => { :active => true }, :order => 'LOWER(first_name), LOWER(last_name) ASC'
这基本上是抓取所有记录,我没有分页,因为我使用的是 jquery datatables 表,它具有很好的过滤器搜索...我想要实现的问题是尽可能缓存这些记录,除非有新用户...这并不经常发生
我读到了 fresh_when 但不知道这里可以用什么
更新
按照下面的答案后,我在日志中没有看到 CACHE,我只看到了
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
最佳答案
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 引起我们的注意。
关于ruby-on-rails - 有没有办法缓存 .all 调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11209617/