Skip to content

Fix reset_counters crashing on has_many :through associations. #7822

Merged
merged 1 commit into from Oct 2, 2012

3 participants

@lulalala
lulalala commented Oct 2, 2012

Currently when a counter cache column name is specified in the intermediate model of a has_many :through association, the reset_counters() method is unable to get the model where the column resides in. The resulting error is:

NoMethodError: undefined method `counter_cache_column' for nil:NilClass

The correct model reference has to be accessed using the additional through_reflection object.

@rafaelfranca
Ruby on Rails member

Could you add a CHANGELOG entry?

@rafaelfranca rafaelfranca commented on the diff Oct 2, 2012
activerecord/lib/active_record/counter_cache.rb
@@ -22,8 +22,13 @@ def reset_counters(id, *counters)
counters.each do |association|
has_many_association = reflect_on_association(association.to_sym)
- foreign_key = has_many_association.foreign_key.to_s
- child_class = has_many_association.klass
+ if has_many_association.is_a? ActiveRecord::Reflection::ThroughReflection
+ foreign_key = has_many_association.through_reflection.foreign_key
@rafaelfranca
Ruby on Rails member
rafaelfranca added a note Oct 2, 2012

Why we are not calling to_s in this foreign_key?

@lulalala
lulalala added a note Oct 2, 2012

Thanks, I missed it. Let me update it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@lulalala lulalala Fix reset_counters() crashing on has_many :through associations.
The counter column name in the intermediate model need to be access
via the through reflection.
6e56a03
@lulalala
lulalala commented Oct 2, 2012

@rafaelfranca Thanks, I have updated the code and the CHANGELOG.

@rafaelfranca rafaelfranca merged commit 2bc1ac7 into rails:master Oct 2, 2012
@rafaelfranca
Ruby on Rails member

Thanks

@artemave

Can anyone please have a look at backport of this for 3-2 stable? #9156 Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.