diff options
author | Stefan Kanev <stefan.kanev@gmail.com> | 2014-08-09 22:19:02 +0300 |
---|---|---|
committer | Sean Griffin <sean@thoughtbot.com> | 2015-07-19 15:52:29 -0600 |
commit | 0ed096ddf5416fefa3afacb72c64632c02826f95 (patch) | |
tree | cc715ac6cf6b362738eb219068612ed12577f4ba /activerecord/lib/active_record | |
parent | 0bd247cc7679adb3c2e30b46ecc9afd57ac46c45 (diff) | |
download | rails-0ed096ddf5416fefa3afacb72c64632c02826f95.tar.gz rails-0ed096ddf5416fefa3afacb72c64632c02826f95.tar.bz2 rails-0ed096ddf5416fefa3afacb72c64632c02826f95.zip |
Fix counter_cache for polymorphic associations
Also removes a false positive test that depends on the fixed bug:
At this time, counter_cache does not work with polymorphic relationships
(which is a bug). The test was added to make sure that no
StaleObjectError is raised when the car is destroyed. No such error is
currently raised because the lock version is not incremented by
appending a wheel to the car.
Furthermore, `assert_difference` succeeds because `car.wheels.count`
does not check the counter cache, but the collection size. The test will
fail if it is replaced with `car.wheels_count || 0`.
Diffstat (limited to 'activerecord/lib/active_record')
-rw-r--r-- | activerecord/lib/active_record/associations/builder/belongs_to.rb | 16 |
1 files changed, 12 insertions, 4 deletions
diff --git a/activerecord/lib/active_record/associations/builder/belongs_to.rb b/activerecord/lib/active_record/associations/builder/belongs_to.rb index 97eb007f62..6e4a53f7fb 100644 --- a/activerecord/lib/active_record/associations/builder/belongs_to.rb +++ b/activerecord/lib/active_record/associations/builder/belongs_to.rb @@ -33,16 +33,24 @@ module ActiveRecord::Associations::Builder if (@_after_create_counter_called ||= false) @_after_create_counter_called = false - elsif attribute_changed?(foreign_key) && !new_record? && reflection.constructable? - model = reflection.klass + elsif attribute_changed?(foreign_key) && !new_record? + if reflection.polymorphic? + model = attribute(reflection.foreign_type).try(:constantize) + model_was = attribute_was(reflection.foreign_type).try(:constantize) + else + model = reflection.klass + model_was = reflection.klass + end + foreign_key_was = attribute_was foreign_key foreign_key = attribute foreign_key if foreign_key && model.respond_to?(:increment_counter) model.increment_counter(cache_column, foreign_key) end - if foreign_key_was && model.respond_to?(:decrement_counter) - model.decrement_counter(cache_column, foreign_key_was) + + if foreign_key_was && model_was.respond_to?(:decrement_counter) + model_was.decrement_counter(cache_column, foreign_key_was) end end end |