Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

validate vs validates_associated

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?

like image 407
Zardoz Avatar asked Nov 19 '10 04:11

Zardoz


People also ask

What is the difference between validate and validates in rails?

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.

What is validate in rails?

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.


1 Answers

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.

like image 69
Ariejan Avatar answered Sep 28 '22 09:09

Ariejan