Merge pull request #44783 from p8/guides/move-validates-associated

Group `validates_associated` guide with `validates_*` [ci-skip]
This commit is contained in:
Petrik de Heus 2022-04-05 21:38:33 +02:00 committed by GitHub
commit f1c079951d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 24 additions and 24 deletions

View File

@ -320,30 +320,6 @@ don't have a field for it, the helper will create a virtual attribute. If
the field does exist in your database, the `accept` option must be set to the field does exist in your database, the `accept` option must be set to
or include `true` or else the validation will not run. or include `true` or else the validation will not run.
### `validates_associated`
You should use this helper when your model has associations with other models
and they also need to be validated. When you try to save your object, `valid?`
will be called upon each one of the associated objects.
```ruby
class Library < ApplicationRecord
has_many :books
validates_associated :books
end
```
This validation will work with all of the association types.
CAUTION: Don't use `validates_associated` on both ends of your associations.
They would call each other in an infinite loop.
The default error message for [`validates_associated`][] is _"is invalid"_. Note
that each associated object will contain its own `errors` collection; errors do
not bubble up to the calling model.
[`validates_associated`]: https://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html#method-i-validates_associated
### `confirmation` ### `confirmation`
You should use this helper when you have two text fields that should receive You should use this helper when you have two text fields that should receive
@ -702,6 +678,30 @@ searches anyway.
The default error message is _"has already been taken"_. The default error message is _"has already been taken"_.
### `validates_associated`
You should use this helper when your model has associations that always need to
be validated. Every time you try to save your object, `valid?` will be called
on each one of the associated objects.
```ruby
class Library < ApplicationRecord
has_many :books
validates_associated :books
end
```
This validation will work with all of the association types.
CAUTION: Don't use `validates_associated` on both ends of your associations.
They would call each other in an infinite loop.
The default error message for [`validates_associated`][] is _"is invalid"_. Note
that each associated object will contain its own `errors` collection; errors do
not bubble up to the calling model.
[`validates_associated`]: https://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html#method-i-validates_associated
### `validates_with` ### `validates_with`
This helper passes the record to a separate class for validation. This helper passes the record to a separate class for validation.