Skip to content
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

Fix in-place modification of shared _counter_cache_columns class attribute #49136

Merged
merged 1 commit into from
Sep 5, 2023

Conversation

fatkodima
Copy link
Member

Fixes #49132.

_counter_cache_columns class attribute is defined on ActiveRecord::Base class and all models share its value. We should not modify it in place, but reassign to it.

@@ -37,7 +37,7 @@ def self.add_counter_cache_callbacks(model, reflection)
}

klass = reflection.class_name.safe_constantize
klass._counter_cache_columns << cache_column if klass && klass.respond_to?(:_counter_cache_columns)
klass._counter_cache_columns |= [cache_column] if klass && klass.respond_to?(:_counter_cache_columns)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@fatkodima Just curious to know, how this exactly fixes the issue. In both cases, we are appending the column to the _counter_cache_columns right?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For << we modify the original object, but for |= we create a new object with the original contents and the new column and assign to the attribute (original object is intact).

@Earlopain
Copy link
Contributor

Just to confirm, this fixes my original issue. That was a strange experience initially since it only reproduced when creating an elasticsearch index but the root cause was probably the models being accessed in a different order which makes a lot of sense.

@ghiculescu ghiculescu added the ready PRs ready to merge label Sep 4, 2023
@kamipo kamipo merged commit ca374bd into rails:main Sep 5, 2023
4 checks passed
@fatkodima fatkodima deleted the fix-counter-caches-var-modification branch September 5, 2023 13:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
activerecord ready PRs ready to merge
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Column not updated when counter_cache columns overlap with model db field
5 participants