Why does after_save not trigger when using touch?
Solution 1
Have you read documentation for touch
method?
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.
Solution 2
If you want after_save
callbacks to be executed when calling touch
on some model, you can add
after_touch :save
to this model.
Solution 3
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 this the doc : http://guides.rubyonrails.org/association_basics.html#touch
Luan D
I am passionate about programming, learn and looking for new technology. My dream is travel to around the world. I am a fullstack Ruby on Rails web application with 3 years experience, maintenance and deploy.
Updated on July 24, 2022Comments
-
Luan D almost 2 years
Recent days , I was trying to cache rails app use Redis store. I have two models:
class Category < ActiveRecord::Base has_many :products after_save :clear_redis_cache private def clear_redis_cache puts "heelllooooo" $redis.del 'products' end end
and
class Product < ActiveRecord::Base belongs_to :category, touch: true end
in controller
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
With this code , the cache worked fine. But when I updated or created new product (I have used touch method in relationship) it's not trigger after_save callback in Category model. Can you explain me why ?
-
Oleg Afanasyev over 7 yearsIf all you need is just to trigger after_save callbacks please use
save
method. -
Ken Ratanachai S. about 2 yearsHow does this work? :save is a special word for callbacks?
-
Aymeric Bouzy aybbyk about 2 yearsit triggers the
save
method after each touch, which will be a no-op, which will in turn trigger theafter_save
callbacks (from what I understood, I'm no expert)