Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does after_save not trigger when using touch?

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 ?

like image 280
Luan D Avatar asked Jan 24 '15 04:01

Luan D


People also ask

What is after_ save in Rails?

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.

How do Rails callbacks work?

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.


1 Answers

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.

like image 176
Philidor Avatar answered Oct 14 '22 23:10

Philidor