Rails Associations: When are they auto-validated?

Written by Suan Yeo

Quiz-time! You have an ActiveRecord model User which :belongs_to an Account. You associate an invalid account to a valid user (both of them still unsaved), and save! the User. This operation should fail with a validation error right? Basically:

user = User.new(email: "somethingvalid@gmail.com")
account = Account.new(name: "&*(@somethinginvalid@$#)")
account.save!

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:

user = User.new(email: "somethingvalid@gmail.com")
account = Account.new(name: "&*(@somethinginvalid@$#)")
account.save!
=> true
account.reload
account.persisted?
=> true
account.name
=> "&*(@somethinginvalid@$#)"

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.