Permalink
Browse files

Fix counter cache when association uses a class_name

The idea of this commits is from
bf28422, which fixes this problem, but
only on AR 4.1+

[fixes #14369]
  • Loading branch information...
1 parent a6b9ea2 commit 64ccb190658d06d1a36ce3d27975bcb4c29cdf85 @arthurnn arthurnn committed Mar 17, 2014
@@ -1,3 +1,9 @@
+* Fix counter cache when association uses a class_name.
+
+ Fixes #14369.
+
+ *arthurnn*
+
* Add support for `Relation` be passed as parameter on `QueryCache#select_all`.
Fixes #14361.
@@ -22,6 +22,7 @@ def build
def add_counter_cache_callbacks(reflection)
cache_column = reflection.counter_cache_column
foreign_key = reflection.foreign_key
+ klass = reflection.class_name.safe_constantize
mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
def belongs_to_counter_cache_after_create_for_#{name}
@@ -43,8 +44,8 @@ def belongs_to_counter_cache_before_destroy_for_#{name}
def belongs_to_counter_cache_after_update_for_#{name}
if (@_after_create_counter_called ||= false)
@_after_create_counter_called = false
- elsif self.#{foreign_key}_changed? && !new_record? && defined?(#{name.to_s.camelize})
- model = #{name.to_s.camelize}
+ elsif self.#{foreign_key}_changed? && !new_record? && #{constructable?}
+ model = #{klass}
foreign_key_was = self.#{foreign_key}_was
foreign_key = self.#{foreign_key}
@@ -61,8 +62,6 @@ def belongs_to_counter_cache_after_update_for_#{name}
model.after_create "belongs_to_counter_cache_after_create_for_#{name}"
model.before_destroy "belongs_to_counter_cache_before_destroy_for_#{name}"
model.after_update "belongs_to_counter_cache_after_update_for_#{name}"
-
- klass = reflection.class_name.safe_constantize
klass.attr_readonly cache_column if klass && klass.respond_to?(:attr_readonly)
end
@@ -815,6 +815,17 @@ def test_self_referential_belongs_to_with_counter_cache_assigning_nil
assert_equal 0, comments(:greetings).reload.children_count
end
+ def test_belongs_to_with_id_assigning
+ post = posts(:welcome)
+ comment = Comment.create! body: "foo", post: post
+ parent = comments(:greetings)
+ assert_equal 0, parent.reload.children_count
+ comment.parent_id = parent.id
+
+ comment.save!
+ assert_equal 1, parent.reload.children_count
+ end
+
def test_polymorphic_with_custom_primary_key
toy = Toy.create!
sponsor = Sponsor.create!(:sponsorable => toy)

0 comments on commit 64ccb19

Please sign in to comment.