There is a validate
specifier that can be directly used on the association (see 4.1.2.12 at this Rails Guide and also a validates_associated
(see 3.2 at that Rails Guide).
Where do both differ?
So remember folks, validates is for Rails validators (and custom validator classes ending with Validator if that's what you're into), and validate is for your custom validator methods.
Validations are used to ensure that only valid data is saved into your database. For example, it may be important to your application to ensure that every user provides a valid email address and mailing address. Model-level validations are the best way to ensure that only valid data is saved into your database.
They both validate the associated model(s).
The difference is that the first is an option on the association (e.g. belongs_to
, has_many
, etc). E.g. you define the 'act of validation' in your association.
In a classic "Author has many Books" example, say you enable belongs_to :author, :validate => true
on the Book model. Every time you validate a Book model, the associated Author must also be valid.
The other is a separate validates rule you can add to your other validations. So, in this case you enable the validation of an associated object together with other validation rules.
This can work the other way around. In Author: has_many :books ; validates_associated :books
. When you validate the Author object, all books are validated as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With