Prevent ActiveRecord from reloading associated records when the STI name is different#27
Merged
doliveirakn merged 2 commits intoclio:masterfrom Dec 18, 2019
Merged
Conversation
When a class' name does not match its STI name, ActiveRecord will reload an associated record from the database even if it's already in memory. This bug exists in Rails 4 and above.
41f84c7 to
ffb91aa
Compare
doliveirakn
approved these changes
Dec 18, 2019
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
When using classes with custom STI names, a bug exists where ActiveRecord will always reload the associated record from the database, even if a valid instance is already loaded.
This occurs because of how we are patching
foreign_type=:We expect that
klasswill be something that we can look up in the foreign type mapping; if we can't look it up, and it's a constant, then we can attempt to find it using itssti_name.However, sometimes Rails passes this method a string instead of a constant. When that happens, our lookup doesn't work and we end up returning
nil. As a result, the associated record is reloaded because ActiveRecord believes it to be stale.This issue only exists in Rails < 5.2. Rails 5.2 introduced a
.polymorphic_namemethod that allows the user to customize this as needed.