小编Lua*_*n D的帖子

为什么在使用触摸时不会触发after_save?

最近几天,我试图使用Redis商店缓存rails app.我有两个型号:

class Category < ActiveRecord::Base
  has_many :products

  after_save :clear_redis_cache

  private

    def clear_redis_cache
      puts "heelllooooo"
      $redis.del 'products'
    end
end
Run Code Online (Sandbox Code Playgroud)

class Product < ActiveRecord::Base
  belongs_to :category, touch: true
end
Run Code Online (Sandbox Code Playgroud)

在控制器中

def index
    @products = $redis.get('products')

    if @products.nil?
      @products = Product.joins(:category).pluck("products.id", "products.name", "categories.name")
      $redis.set('products', @products)
      $redis.expire('products', 3.hour.to_i)
    end

    @products = JSON.load(@products) if @products.is_a?(String)

  end
Run Code Online (Sandbox Code Playgroud)

使用此代码,缓存工作正常.但是当我更新或创建新产品(我在关系中使用了触摸方法)时,它不会触发Category模型中的after_save回调.你能解释一下为什么吗?

ruby caching ruby-on-rails ruby-on-rails-4

12
推荐指数
3
解决办法
7132
查看次数

标签 统计

caching ×1

ruby ×1

ruby-on-rails ×1

ruby-on-rails-4 ×1