【问题标题】:Why does after_save not trigger when using touch?为什么使用触摸时 after_save 不触发?
【发布时间】:2015-03-23 05:29:11
【问题描述】:

最近几天,我试图缓存 Rails 应用程序使用 Redis 商店。 我有两个模型:

class Category < ActiveRecord::Base
  has_many :products

  after_save :clear_redis_cache

  private

    def clear_redis_cache
      puts "heelllooooo"
      $redis.del 'products'
    end
end

class Product < ActiveRecord::Base
  belongs_to :category, touch: true
end

在控制器中

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

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

【问题讨论】:

    标签: ruby-on-rails ruby caching ruby-on-rails-4


    【解决方案1】:

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

    使用设置为当前的 updated_at/on 属性保存记录 时间。 请注意,不执行验证,仅执行 after_touch、after_commit 和 after_rollback 回调被执行。 如果传递了属性名称,则该属性将与 updated_at/on 属性。

    【讨论】:

    • 如果您只需要触发 after_save 回调,请使用save 方法。
    【解决方案2】:

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

    after_touch :save
    

    到这个模型。

    【讨论】:

      【解决方案3】:

      如果您将 :touch 选项设置为 :true,那么每当该对象保存销毁时,关联对象上的 updated_at 或 updated_on 时间戳将设置为当前时间强> 这是文档: http://guides.rubyonrails.org/association_basics.html#touch

      【讨论】:

        猜你喜欢
        • 2022-08-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-20
        • 2010-11-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多