association snippets

ActiveRecord after_create/after_save and associations

Tagged after_create, after_save, association, rails  Languages ruby

The order of ActiveRecord callbacks matter when, for example, using associations (e.g. has_many).

For example, the calculate_doors hook will be called before the associations are saved to the database if you use :backdoor):

class Car < ApplicationRecord
  after_create :calculate_doors
  has_many :doors

This can lead to subtle errors.

Changing the order will fix the issue:

class Car < ApplicationRecord
  has_many :doors
  after_create :create_doors

Tested with Rails 6.1. Other versions might work differently.

See for details:

Placing your callbacks after associations is usually a good practice.