提交 1e27f1c5 编写于 作者: M Matthew Robertson

Update counter cache when pushing into association

This commit fixes a regression bug in which counter_cache columns
were not being updated correctly when newly created records were
being pushed into an assocation. EG:

    # this was fine
    @post.comment.create!

    # this was fine
    @comment = Comment.first
    @post.comments << @comment

    # this would not update counters
    @post.comments << Comment.create!
上级 fae07a81
## Rails 4.0.0 (unreleased) ##
* Fix for a regression bug in which counter cache columns were not being updated
when record was pushed into a has_many association. For example:
Post.first.comments << Comment.create
Fixes #3891.
*Matthew Robertson*
* If a model was instantiated from the database using `select`, `respond_to?`
returns false for non-selected attributes. For example:
......
......@@ -25,9 +25,10 @@ def add_counter_cache_callbacks(reflection)
mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
def belongs_to_counter_cache_after_create_for_#{name}
record = #{name}
record.class.increment_counter(:#{cache_column}, record.id) unless record.nil?
@_after_create_counter_called = true
if record = #{name}
record.class.increment_counter(:#{cache_column}, record.id)
@_after_create_counter_called = true
end
end
def belongs_to_counter_cache_before_destroy_for_#{name}
......
......@@ -755,6 +755,15 @@ def test_deleting_updates_counter_cache
assert_equal topic.replies.to_a.size, topic.replies_count
end
def test_pushing_association_updates_counter_cache
topic = Topic.order("id ASC").first
reply = Reply.create!
assert_difference "topic.reload.replies_count", 1 do
topic.replies << reply
end
end
def test_deleting_updates_counter_cache_without_dependent_option
post = posts(:welcome)
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册