【问题标题】:How to activerecord cache in Rails 3.2.3如何在 Rails 3.2.3 中激活记录缓存
【发布时间】:2012-05-22 10:54:35
【问题描述】:

如何在 Rails 3.2.3 中激活记录缓存

stocks_controller.rb:

def index
  @stocks = Rails.cache.read custom_cache_path(@res.uuid, Const::ACTIVE_STOCKS)
  if @stocks.blank?
    @stocks = Stock.only_active_stocks(params[:restaurant_id])
    Rails.cache.write custom_cache_path(@res.uuid, Const::ACTIVE_STOCKS), @stocks
  end
end

def show
  @stocks = Rails.cache.read custom_cache_path(@res.uuid, Const::ACTIVE_STOCKS)
  if @stocks.blank?
    @stocks = Stock.only_active_stocks(params[:restaurant_id])
    Rails.cache.write custom_cache_path(@res.uuid, Const::ACTIVE_STOCKS), @stocks
  end
end

对显示操作缓存的请求何时返回 nil?

【问题讨论】:

    标签: ruby-on-rails-3 caching activerecord memcached


    【解决方案1】:

    这里很难理解你在控制器中的意图,因为你的 show 和 index 方法都有相同的实现。

    话虽如此,您可能希望将任何缓存逻辑移入此处的模型中,这样更容易隔离您的问题。

    请考虑以下重构:

    stocks_controller:

    def index
      @stocks = Stock.active_for_restaurant(params[:restaurant_id])
    end
    
    def show
      @stock = Stock.fetch_from_cache(params[:id])
    end
    

    股票.rb:

    def active_for_restaurant(restaurant_id)
      Rails.cache.fetch(custom_cache_path(restaurant_id, Const::ACTIVE_STOCKS)) do
        Stock.only_active_stocks(restaurant_id)
      end
    end
    
    def fetch_from_cache(id)
      Rails.cache.fetch(id, find(id))
    end
    

    有关 fetch 的更多信息,请参阅: http://api.rubyonrails.org/classes/ActiveSupport/Cache/Store.html#method-i-fetch

    【讨论】:

    • 不管缓存命中/未命中,Rails.cache.fetch(id, find(id)) 不会总是命中数据库吗?
    【解决方案2】:

    正如 rails api 所说 - 如果缓存中没有此类数据(缓存未命中),则将返回 nil。这是你的问题吗?

    顺便说一句,请确保在“active_stocks”更改时更新缓存。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-10
      • 1970-01-01
      • 2017-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-07
      相关资源
      最近更新 更多