Getting Touchy With ActiveRecord Callbacks

A client wants each receipt to store its total. Add a $10 item to a receipt with $2 in tax and the total should read $12. Change the item to $15 and the same receipt should read $17. The interesting part is the second write. The user edited an item, but the amount that needs to change lives on its parent.

What does touch actually do?

Calling receipt.touch on a persisted receipt updates its timestamp. With PostgreSQL, the write looks roughly like this:

UPDATE "receipts" SET "updated_at" = $1 WHERE "receipts"."id" = $2;

Rails then runs the receipt’s after_touch callbacks. It skips validations and the normal save callbacks on that touch. With belongs_to :receipt, touch: true, saving a changed item or destroying it also touches its receipt. That gives us two places to keep the stored amount current. Active Record callbacks

Two ways the amount can change

For this example, items.price, receipts.taxes, and receipts.amount are non-null decimal columns. Both tables have timestamps. Taxes are a currency amount, and an empty receipt starts with just its taxes.

class Item < ApplicationRecord
  belongs_to :receipt, touch: true
  validates :price, numericality: true
end

class Receipt < ApplicationRecord
  has_many :items
  validates :taxes, numericality: true

  before_save :assign_amount
  after_touch :refresh_amount

  private

  def total_with_tax
    items.sum(:price) + taxes
  end

  def assign_amount
    self.amount = total_with_tax
  end

  def refresh_amount
    update_column(:amount, total_with_tax)
  end
end

When the receipt’s taxes change, before_save assigns the amount in memory. Rails includes that value in the save already underway. When an item changes, the receipt gets a touch instead. Assigning self.amount in after_touch would only change the Ruby object. Here update_column writes the one derived column without starting another save.

The 2015 version used update_attribute for that last step. It skips validations but still runs save callbacks, and it can persist other dirty attributes on the object. update_column skips both validations and callbacks. I use it narrowly here because the target is a derived value and the touch already updated the timestamp. Active Record persistence methods

Try it in the console

Run each write as its own transaction and reload the receipt to check what actually reached the database.

receipt = Receipt.create!(taxes: 2)
item = receipt.items.create!(price: 10)
receipt.reload.amount          # => 12
item.update!(price: 15)
receipt.reload.amount          # => 17
receipt.update!(taxes: 3)
receipt.reload.amount          # => 18
item.destroy!
receipt.reload.amount          # => 3

When I would store the total

If all I need is a number on a page, I can calculate items.sum(:price) + taxes when I read the receipt. Storing it makes sense when something else needs to query that column. It also means every write path has to maintain it. For example, items.update_all bypasses the item callbacks, so a bulk price change needs an explicit recalculation. If several writers can edit the same receipt at once, I would serialize those changes around the receipt and test that path before relying on the stored total.