Quiz-time! You have an ActiveRecord model
Account. You associate an invalid account to a valid user (both of them still unsaved), and
User. This operation should fail with a validation error right? Basically:
The answer is: it depends. ActiveRecord doesn’t validate associations unless you explicitly tell it to (via
validates_associated), or if they are mandatory (a.k.a. the base model has a
validates_presence_of) If it doesn’t, ActiveRecord happily saves the association without first validating it:
Note that if you have equivalent validations at the database level, saving the association will (more expectedly) fail and the entire operation will be rolled back (since ActiveRecord automatically wraps
#save! operations in transactions) This is a good argument for ensuring you have validations at both the ActiveRecord and database-level.
Rails and ActiveRecord provide so many niceties that it’s easy to take them for granted - this is one of those cases to watch out for though.