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
ActiveRecord updates counters when it shouldn't #41250
Comments
@milani are you panning to open a PR to fix this? Otherwise I'd give it a try. |
@intrip not really. I am not sure about the best conditions to add there. |
Allright, I'll take a look 🙂 |
This issue has been automatically marked as stale because it has not been commented on for at least three months. |
Attached PR. Still relevant |
Fix when multiple `belongs_to` maps to the same counter_cache column. In such situation `inverse_which_updates_counter_cache` may find the wrong relation which leads into an invalid increment of the counter_cache. This is done by improving the inverse relation detection in 2 ways: - by comparing `inverse.klass` with the current `active_record` (doesn't work for polymorphic) - by relying on `inverse_of` The above adjustments allows to correctly map the `inverse_which_updates_counter_cache` for both non-polymorphic/polymorphic relations. Fixes rails#41250
This issue has been automatically marked as stale because it has not been commented on for at least three months. |
Attached PR. Still relevant |
Can someone take a look at the PR and review it? |
This issue has been automatically marked as stale because it has not been commented on for at least three months. |
not stale, will update the PR in the next days. |
Fix when multiple `belongs_to` maps to the same counter_cache column. In such situation `inverse_which_updates_counter_cache` may find the wrong relation which leads into an invalid increment of the counter_cache. This is done by releying on the `inverse_of` property of the relation as well as comparing the models the association points two. Note however that this second check doesn't work for polymorphic associations. Fixes rails#41250 Co-Authored-By: Jean Boussier <jean.boussier@gmail.com>
Steps to reproduce
Here is a test case:
Expected Behaviour
The test should pass. Since there is no
counter_cache
defined for the comments-posts relation, I don't expect its counters get the updates.Actual Behaviour
The test fails:
The Cause
It is happening because a
belongs_to
relation is defined for theUser
model. The root of the problem is here:rails/activerecord/lib/active_record/reflection.rb
Lines 250 to 255 in 291a3d2
It needs a more strict condition to determine the inverse relation.
The text was updated successfully, but these errors were encountered: