Merge pull request #7822 from lulalala/reset-counter-cache-for-has-many-through

Fix reset_counters crashing on has_many :through associations.
Conflicts:
	activerecord/CHANGELOG.md
	activerecord/lib/active_record/counter_cache.rb
This commit is contained in:
Rafael Mendonça França
2012-10-02 09:23:02 -07:00
parent 2bad605873
commit 3f0bc97912
5 changed files with 29 additions and 4 deletions

View File

@@ -1,5 +1,10 @@
## Rails 3.2.9 (unreleased)
* Fix `reset_counters` crashing on `has_many :through` associations.
Fix #7822.
*lulalala*
* ConnectionPool recognizes checkout_timeout spec key as taking
precedence over legacy wait_timeout spec key, can be used to avoid
conflict with mysql2 use of wait_timeout. Closes #7684.

View File

@@ -25,8 +25,14 @@ module ActiveRecord
self.name
end
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.to_s
child_class = has_many_association.through_reflection.klass
else
foreign_key = has_many_association.foreign_key.to_s
child_class = has_many_association.klass
end
belongs_to = child_class.reflect_on_all_associations(:belongs_to)
reflection = belongs_to.find { |e| e.foreign_key.to_s == foreign_key && e.options[:counter_cache].present? }
counter_name = reflection.counter_cache_column

View File

@@ -10,9 +10,12 @@ require 'models/dog'
require 'models/dog_lover'
require 'models/person'
require 'models/friendship'
require 'models/subscriber'
require 'models/subscription'
require 'models/book'
class CounterCacheTest < ActiveRecord::TestCase
fixtures :topics, :categories, :categorizations, :cars, :dogs, :dog_lovers, :people, :friendships
fixtures :topics, :categories, :categorizations, :cars, :dogs, :dog_lovers, :people, :friendships, :subscribers, :subscriptions, :books
class ::SpecialTopic < ::Topic
has_many :special_replies, :foreign_key => 'parent_id'
@@ -118,4 +121,14 @@ class CounterCacheTest < ActiveRecord::TestCase
Person.reset_counters(michael.id, :followers)
end
end
test "reset counter of has_many :through association" do
subscriber = subscribers('second')
Subscriber.reset_counters(subscriber.id, 'books')
Subscriber.increment_counter('books_count', subscriber.id)
assert_difference 'subscriber.reload.books_count', -1 do
Subscriber.reset_counters(subscriber.id, 'books')
end
end
end

View File

@@ -1,4 +1,4 @@
class Subscription < ActiveRecord::Base
belongs_to :subscriber
belongs_to :subscriber, :counter_cache => :books_count
belongs_to :book
end

View File

@@ -596,6 +596,7 @@ ActiveRecord::Schema.define do
create_table :subscribers, :force => true, :id => false do |t|
t.string :nick, :null => false
t.string :name
t.column :books_count, :integer, :null => false, :default => 0
end
add_index :subscribers, :nick, :unique => true