ruby-on-rails – 为什么在使用触摸时不会触发after_save?

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 为什么在使用触摸时不会触发after_save?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
最近几天,我试图使用Redis商店缓存rails app.
我有两个型号:
  1. class Category < ActiveRecord::Base
  2. has_many :products
  3.  
  4. after_save :clear_redis_cache
  5.  
  6. private
  7.  
  8. def clear_redis_cache
  9. puts "heelllooooo"
  10. $redis.del 'products'
  11. end
  12. end

  1. class Product < ActiveRecord::Base
  2. belongs_to :category,touch: true
  3. end

在控制器中

  1. def index
  2. @products = $redis.get('products')
  3.  
  4. if @products.nil?
  5. @products = Product.joins(:category).pluck("products.id","products.name","categories.name")
  6. $redis.set('products',@products)
  7. $redis.expire('products',3.hour.to_i)
  8. end
  9.  
  10. @products = JSON.load(@products) if @products.is_a?(String)
  11.  
  12. end

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

解决方法

您是否阅读过 touch方法的文档?

Saves the record with the updated_at/on attributes set to the current
time. Please note that no validation is performed and only the after_touch,after_commit and after_rollback callbacks are executed. If an attribute name is passed,that attribute is updated along with updated_at/on attributes.

猜你在找的Ruby相关文章