簡體   English   中英

Rails 控制器操作中的查詢緩存

[英]Query caching in Rails controller action

我正在為用戶控制器索引操作使用查詢緩存。

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

有人可以幫我解決這個問題。 謝謝

你想讓 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM