rails
rails copied to clipboard
ActiveRecord: Always use NestedError in association validation
Summary
When an association record about to be auto-saved fails validation, the validation error is wrapped in a NestedError
, but only if the association is defined with autosave: true
(see ActiveRecord::AutosaveAssociation#association_valid?). Otherwise just a plain error is created without additional context. So if you are interested in the detailed NestedError
s, you have to enable autosave: true
– validate: true
is not enough.
I don't see any good reason for this difference. The logic was originally added in 5cda000bf0f6d85d1a1efedf9fa4d0b6eaf988a1 but without any explanation. A NestedError with full context seems useful in any case.
Steps to reproduce
Test case based on bug report template: https://gist.github.com/c960657/3d4667bfd9709c86bfb4c732d718d6e6
Other Information
If one prefers just a single validation error, the validates_association
validator still just creates one error for any number of invalidation errors on associated objects, possible with a custom message
. If a message
is supplied, it doesn't seem useful to create a NestedError for each invalidation error, because they would all have the same message.
One might consider modifying Errors#messages_for
, Errors#added?
etc. to do a prefix search, i.e. so that Errors#messages_for("foo")
would match errors with attribute foo
as well as foo.bar
and foo[1].bar
. This would provide the best of both worlds for the two different ways of handling errors .
This pull request has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.
This looks like a reasonable PR to me that deserves consideration. I can't think of a reason why the result of validation should depend on whether :autosave behavior has been declared for an association.
Superficially one might argue, plain and :autosave associations behave differently, or even inconsistently wrt persisting. But validation is a concern unrelated to the pragmatics of persisting, and not a consequence of this same tradeoff.
I think it makes sense and is probably closer to user expectations if :autosave is transparent with regard to validation.
I have created a test case that shows this bug/issue: https://gist.github.com/c960657/3d4667bfd9709c86bfb4c732d718d6e6