imageable.touch

使用 callback 确保创建,更新和删除 Picture 时,touch 关联的 imageable,使得其缓存能正确过期

这个update的方法用来把update时间强制更新成当前时间

http://guides.rubyonrails.org/association_basics.html

4.1.2.9 :touch

If you set the :touch option to true, then the updated_at or updated_on timestamp on the associated object will be set to the current time whenever this object is saved or destroyed:

class Book < ApplicationRecord
  belongs_to :author, touch: true
end
 
class Author < ApplicationRecord
  has_many :books
end

由于在多态关联中直接写touch :true没有起作用,写了另一个方法

class Picture < ApplicationRecord
  belongs_to :imageable, polymorphic: true                             
                                                                       
  validates_uniqueness_of :name, scope: [:imageable_id, :imageable_type]
                                                                       
  after_save :touch_imagable
  after_destroy :touch_imagable
                                                                       
  def touch_imagable
    imageable.touch                                                    
  end                                                                  
end  
原文地址:https://www.cnblogs.com/iwangzheng/p/5864639.html