ActiveRecord gives a lot of flexibility with its 16 callbacks. I’ve never needed anything more granular than that flexibilty until today.

In trying to automate the process of saving files on Amazon S3, I needed a callback that would be triggered after the creation of my “Photo” record, but before the creation of several associated objects. (These ActiveRecord objects were being held in memory via the association “build” method, and thus had not yet been inserted in to the database.)

Delving deep in to ActiveRecord to figure out how those build-associated objects were being automatically inserted in to the database when calling “save” on my Photo object, I found out it’s a lot easier than it might seem.

Just define your “after_create” callback before the call to “has_many” in your class. For example:


class Photo < ActiveRecord::Base
  # This callback must be defined before "has_many :versions" so
  # that it gets called *after* the Photo is created, but *before*
  # the versions are inserted in to the DB.
  after_create :send_id_to_versions

  has_many :versions

  def send_id_to_versions
    ...
  end
end

If you switch the order of the after_create and the has_many above, the “Version” objects will be inserted to your database before the call to “send_id_to_versions”.

Hope that saved you an hour or two! ;)