Skip to content
Browse files

Merge pull request #14410 from arthurnn/fix_14369

Fix counter cache when association uses a class_name
  • Loading branch information...
2 parents a6b9ea2 + 64ccb19 commit 7549dbac1336491c0b16ef94ce399b9a5ed2ee11 @chancancode chancancode committed Mar 17, 2014
View
6 activerecord/CHANGELOG.md
@@ -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.
View
7 activerecord/lib/active_record/associations/builder/belongs_to.rb
@@ -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
View
11 activerecord/test/cases/associations/belongs_to_associations_test.rb
@@ -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 7549dba

Please sign in to comment.
Something went wrong with that request. Please try again.