Creating multiple ActiveRecord objects within a Rails controller (and rolling back)
Assume you're creating two ActiveRecord objects in a Rails controller, the child object belonging to a has_one relationship to the parent. Assume you need the parent object to exist before the child can be created. If the creation of the child object fails (due to a failure in valdiations for e.g.), how do you make sure that the first one does not persist, and is also deleted?
Enter ActiveRecord transactions.
As can be seen from the gist above, if the 'child' object is not valid, raise an ActiveRecord::Rollback error within the transaction, and ActiveRecord will rollback all 'commits' within the transaction and you won't be left with a dangling parent object.
Nifty.