Last Updated: November 22, 2018
·
11.28K
· michiels

Use before/after callbacks when touch-ing your Rails models

In Rails, using "touch" to update timestamps on your models is awesome. For example when you want to implement <a href="http://37signals.com/svn/posts/3113-how-key-based-cache-expiration-works">key-based cache expiration</a>.

Just like updating, saving and creating models you can also use after_ and before_ callbacks for touch on your Rails models.

class Product < ActiveRecord::Base

  after_touch :update_cached_stock

  def combined_stock
    # Fetch some stock from various places that you can't
    # do in a simple SQL query.

    return my_combined_stock
  end

  private

  def update_cached_stock
    update_attribute(:cached_stock, self.combined_stock)
  end
end

In an application we are developing, there are various things and related models that could influence a product's stock. (We import from a SAP database, but also process web orders and generate invoices).

Doing something like @product.touch in a background job which automatically updates stock so we can do Product.order(:cached_stock).paginate in a controller is awesome this way.

1 Response
Add your response

before_touch does not exist (at least in Rails 4), only after_touch

over 1 year ago ·