Ruby on rails 有没有办法缓存.all调用?

Ruby on rails 有没有办法缓存.all调用?,ruby-on-rails,ruby,ruby-on-rails-3,caching,Ruby On Rails,Ruby,Ruby On Rails 3,Caching,例如,我的索引控制器中有这个 @users = User.current 这是我的用户模型 scope :current, :conditions => { :active => true }, :order => 'LOWER(first_name), LOWER(last_name) ASC' 这基本上就是抓取所有记录,我没有分页,因为我使用的是jquery datatables表,它有一个很好的过滤器搜索。。。我想解决的问题是,如果可能的话,缓存这些数据,除非有新用

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

@users = User.current
这是我的用户模型

 scope :current, :conditions => { :active => true }, :order => 'LOWER(first_name), LOWER(last_name) ASC'
这基本上就是抓取所有记录,我没有分页,因为我使用的是jquery datatables表,它有一个很好的过滤器搜索。。。我想解决的问题是,如果可能的话,缓存这些数据,除非有新用户……这并不经常发生

我什么时候读过关于fresh_的书,但不知道这里可以用什么

更新

根据下面的答案,我在日志中看不到缓存

  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
这就是你想要的。请在此处阅读更多信息:


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

更新

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

您的解决方案似乎很棒,但当我查看日志时,我看不到缓存,每次都会看到普通sql…我会更新我的问题哦,是的。。。默认情况下,在开发中已禁用缓存。。。请参阅editOne reservation--Rails在默认情况下使用
FileStore
进行封送/解封,这可能比直接SQL慢(取决于本地磁盘),此外,它在R3.2Strange中默认启用,因为我将config.action\u controller.perform\u caching更改为true,但仍然没有在开发日志中看到缓存……我重新启动了sql,但仍然是纯sql……如果需要,我使用的是rails 3.2.6。如果要使用rails.cache,则需要调用。all(或类似)在你的作用域上,或者你只缓存作用域对象,而不是它的执行结果。你的数据库中有多少用户?你有没有找到解决方案?我也有同样的问题(
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.action_controller.perform_caching = true
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