mirror of https://github.com/rails/rails
Merge pull request #44783 from p8/guides/move-validates-associated
Group `validates_associated` guide with `validates_*` [ci-skip]
This commit is contained in:
commit
f1c079951d
|
@ -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
|
||||
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`
|
||||
|
||||
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"_.
|
||||
|
||||
### `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`
|
||||
|
||||
This helper passes the record to a separate class for validation.
|
||||
|
|
Loading…
Reference in New Issue