【问题标题】:Query caching in Rails controller actionRails 控制器操作中的查询缓存
【发布时间】:2020-03-19 04:03:43
【问题描述】:

我正在为用户控制器索引操作使用查询缓存。

def index
   @users = User.all
   json_response @users
end

我按照rails cast视频并在用户控制器中添加了这样的内容。

   def index
     @users = User.cached_data
     json_response @users
   end

在用户模型中,我添加了 cached_data 方法。

  def self.cached_data
   Rails.cache.fetch([])   // I am not getting how to do caching here and get all the users data
  end

有人可以帮我解决这个问题。 谢谢

【问题讨论】:

标签: ruby-on-rails


【解决方案1】:

你想让 Rails.cache.fetch 变成这样的块:

    def self.cached_data
      Rails.cache.fetch("all_users", expires_in: 2.hours) do
        # add your query here
        User.all
      end
    end

cache_key 可以是你想要的任何东西,并且 expires_in: 是可选的,但我总是在其中添加它,除非 cache_key 基于时间戳或其他会自动使缓存过期的东西。

此外,此文档页面仍然有效:

https://guides.rubyonrails.org/caching_with_rails.html#low-level-caching

【讨论】:

    猜你喜欢
    • 2015-11-12
    • 1970-01-01
    • 2014-07-19
    • 1970-01-01
    • 2017-08-19
    • 2017-01-12
    • 1970-01-01
    • 2018-01-14
    • 1970-01-01
    相关资源
    最近更新 更多