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 ?
The after_save callback will be triggered irrespective its a save or an update on that object. Also, update_column doesn't trigger any callbacks(ie after_update) and skips validations too.
Callbacks are methods that get called at certain moments of an object's life cycle. With callbacks it is possible to write code that will run whenever an Active Record object is created, saved, updated, deleted, validated, or loaded from the database.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With