You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Fix find_or_create_by! not checking owner persistence:
- Fixrails#54920
- ### Problem
In rails#54845, I modified a call to `Record#create` for
`Record#new` followed by `Record#save`. I didn't seen that the
behaviour between both is different on associations.
https://github.com/rails/rails/blob/b97917da8a801bf5360c3a9da913415bc8582735/activerecord/lib/active_record/associations/collection_association.rb#L355-L356
```ruby
car = Car.new
car.wheels.create # Check if `car` is persisted before creating a wheel.
wheel = car.wheels.new
wheel.save # Doesn't check if `car` is persisted
```
### Solution
The original reason why I modified `#create` is because it doesn't
allow to get the result of the transaction status within
a nested transaction. The documentation explains it and mention
to raise a rollback so that the outer transaction sees it but it misses
an important detail: How to know whether the inner transaction was
sucessfull since the Rollback error is silently swallowed.
https://github.com/rails/rails/blob/b97917da8a801bf5360c3a9da913415bc8582735/activerecord/lib/active_record/transactions.rb#L159-L165
A very simple example:
```ruby
class Car < ApplicationRecord
after_save do
raise ActiveRecord::Rollback
end
end
Car.transaction do
car = Car.create!
puts car.persisted? # Returns true. That's not correct.
end
```
The solution in this patch is to provide a flag on the record to know
whether the last transaction was succesful.
0 commit comments