ruby-on-rails-3 - 如何在 Rails 3.2.3 中激活记录缓存

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

如何在 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?

最佳答案

很难理解您在 Controller 中的意图,因为您的 show 和 index 方法具有相同的实现。

话虽如此,您可能希望将任何缓存逻辑移至此处的模型中,这样就可以更轻松地隔离您的问题。

请考虑以下重构:

股票 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

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

关于ruby-on-rails-3 - 如何在 Rails 3.2.3 中激活记录缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10700611/

相关文章:

ruby-on-rails-3 - 使用 Carrierwave 上传到 Rackspace 时出现 Fog::Storage::Rackspace::NotFound 错误

sql-server - 批量调用存储过程时SQLCLR状态持久化

mysql - Rails Mysql ActiveRecord::ConnectionNotEstablished

ruby-on-rails - 包含避免关系默认范围的 ActiveRecord 查询

php - 是否可以将 PDO 准备好的语句存储在 PHP/Mysql/APC/Memcache 中以供重用?

ruby - 初始ElasticSearch批量索引/插入/上传确实很慢,如何提高速度?

ruby-on-rails - 如何使用 Capistrano gem 为生产数据库播种?

ruby-on-rails - 在一页上列出并创建 rails 3

ruby-on-rails - 如何在 gmaps4rails 上配置其他属性?

nginx - 如何为 REST API 正确配置 Nginx 缓存?