Use foreign_key to reference parent association #548
Merged
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.
After a db update happens on a child record, identity_cache has mechanisms to invalidate the cache on associated parent records that have the child record as an embedded cache association (ex.
cache_has_many :children, embed: true
). This works even for "old" parent records where the child incurs an update where it no longer belongs to the old parent - identity cache is designed to invalidate the cache on the old parent record as well.To know which parent records to invalidate the cache for, identity_cache first understands which attributes on the child records changed, then detects which of those changes are for parent associations. The second step uses the Rails
association_foreign_key
attribute. This works in most cases, but there is a bug when it comes to associations defined with custom foreign keys. Take the following example:When calling
association_foreign_key
on the association, Rails gives backparent_id
, which is inappropriate for us to use in the context of detecting attribute changes on the child record. The correct key to use isperson_id
, ie the actual db column that ties the two models together, which is what gets passed back withforeign_key
.From the Rails docs, it seems that
association_foreign_key
is intended to be useful forhas_and_belongs_to_many
type associations (option is only defined under that section). While from the docs, it's clearforeign_key
is a well-supported option across all the association types.Looking at the history of the repo,
association_foreign_key
was used since the very early days of the gem. I believe it was introduced in error, and the bug hasn't been prominent enough to warrant a revisit.✅ Ran CI on shopify core to ensure no regression