加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 有没有办法缓存.all调用?

发布时间:2020-12-17 03:21:58 所属栏目:百科 来源:网络整理
导读:例如,我在我的索引控制器中有这个 @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_when的内容,但不知道这里可以使用什么

UPDATE

按照下面的答案后,我没有在日志中看到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

UPDATE注意.all在User.where().order().all中.all.没有它,存储在缓存中的值只是一个ActiveRecord关系而不是实际结果.如果没有.all,仍然需要运行查询.感谢@Frederick Cheung引起我们的注意.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读