uzty4a
Last Updated: February 25, 2016
·
1.551K
· artchang

Start background jobs after_commit when creating a new record

When you create a new record with ActiveRecord, you get all your commit hooks fired off in all sorts of different orders.

When you want to start a background job that does a lookup of your newly created record, you simply pass the job the primary key, probably id. This is so you don't need to marshall a big 'ol record into it. The background job does a simple find, then does what you need.

When you do this, the only hook that ensures your record was created and committed to the database is aftercommit. If you fire off your background job in an aftersave or after_create, the background job might start even before your record is committed to the database, thus throwing a RecordNotFound error.

after_commit is fired after the transaction to the database is committed, and you can safely then start your background job. To specify it during a create only transaction, you can specify it this way:

after_commit :process_photos, :on => :create

Hope that helps!