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

Lua*_*n D 12 ruby caching ruby-on-rails ruby-on-rails-4

最近几天,我试图使用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回调.你能解释一下为什么吗?

Зел*_*ный 28

你读过文档吗? touch方法的吗?

使用设置为当前时间的updated_at/on属性保存记录. 请注意,不执行验证,只执行after_touch,after_commit和after_rollback回调. 如果传递了属性名称,则会更新该属性以及updated_at/on属性.

  • 如果您只需要触发 **after_save** 回调,请使用 `save` 方法。 (2认同)

Aym*_*byk 6

如果您希望after_save在调用touch某个模型时执行回调,则可以添加

after_touch :save
Run Code Online (Sandbox Code Playgroud)

到这个模型.

  • 它会在每次触摸后触发“save”方法,这将是一个无操作,这将依次触发“after_save”回调(据我所知,我不是专家) (2认同)

sco*_*txu 1

如果将 :touch 选项设置为 :true,则每当保存销毁该对象时,关联对象上的 Updated_at 或 Updated_on 时间戳将设置为当前时间 :http: //guides.rubyonrails.org/association_basics .html#touch