-
Notifications
You must be signed in to change notification settings - Fork 21.4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Regression saving in an after_create with a uniqueness validation #23844
Comments
To be clear, this was also working in 4.2, right? |
Yes, this was working in 4.2. |
Here's what it looks like on 4.2.5:
The id exclusion looks very similar to Rails 5.0.0.beta2 and works as I'd expect, unlike rails master. Using this recreation script:
|
Thanks @matthewd, I have updated the issue description to clarify it's failing on master and was working on 5.0.0.beta2 and 4.2.5. |
/cc @diego-silva |
record.id_was is nil in after_create/after_save, so we should use id in these cases. While this logic feels incomplete, the existing update_record uses the same logic: https://github.com/rails/rails/blob/2fda4e0874a97a76107ab9e88305169f2c625933/activerecord/lib/active_record/relation.rb#L83 This logic was originally added for a similar problem: updates not working with after_create hook. See: 482f8c1 Followup to #23581 Fixes #23844
Currently, on master, if you save a record in an
after_create
on a model with a uniqueness validation, the validation always fails. This was previously working in 5.0.0.beta2 and also works on rails 4.2.5.I have git bisected this to: #23581
Note: From #23581, changing from
id
toid_was
breaksafter_create
andafter_save
callbacks becauseid_was
trailsid
for these callbacks. In other words, theid_was
value is the pre-save/pre-create value. In my example below,id_was
is nil in theafter_create
, whileid
is not nil.Full recreation script and output is here:
https://gist.github.com/jrafanie/083fff24b2c1532d2545
With rails master:
Because
id_was
is nil, the validation query from the gist above looks like this:Note, the "topics"."id" where clause doesn't exclude itself, the just saved object, so the validation fails!
With gem 'rails', "=5.0.0.beta2":
The validation works correctly by issuing the following query:
Note, the "topics"."id" where clause excludes itself, the just saved object, so the validation passes.
I have hacked the change from #23581 to use the
id
ifid_was
is nil and all tests pass. Clearly, this isn't correct but I wanted to try the easiest thing.The text was updated successfully, but these errors were encountered: