aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/test
diff options
context:
space:
mode:
authorSean Griffin <sean@thoughtbot.com>2014-06-15 19:16:30 -0600
committerSean Griffin <sean@thoughtbot.com>2014-06-16 09:40:16 -0600
commite6690d37204dbd7154d275df75d9d0f98f5d2526 (patch)
treee4485022f5f2e8e1c42581cf968184a9b50b07aa /activerecord/test
parentf59ed560ac68aad47e56b6b0442b0b855ae9951e (diff)
downloadrails-e6690d37204dbd7154d275df75d9d0f98f5d2526.tar.gz
rails-e6690d37204dbd7154d275df75d9d0f98f5d2526.tar.bz2
rails-e6690d37204dbd7154d275df75d9d0f98f5d2526.zip
Always update counter caches in memory when adding records
Before, calling `size` would only work if it skipped the cache, and would return a different result from the cache, but only if: - The association was previously loaded - Or you called size previously - But only if the size was 0 when you called it This ensures that the counter is appropriately updated in memory.
Diffstat (limited to 'activerecord/test')
-rw-r--r--activerecord/test/cases/associations/has_many_associations_test.rb30
1 files changed, 30 insertions, 0 deletions
diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb
index 5f01352ab4..3c0b735607 100644
--- a/activerecord/test/cases/associations/has_many_associations_test.rb
+++ b/activerecord/test/cases/associations/has_many_associations_test.rb
@@ -772,6 +772,36 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert_equal topic.replies.to_a.size, topic.replies_count
end
+ def test_counter_cache_updates_in_memory_after_concat
+ topic = Topic.create title: "Zoom-zoom-zoom"
+
+ topic.replies << Reply.create(title: "re: zoom", content: "speedy quick!")
+ assert_equal 1, topic.replies_count
+ assert_equal 1, topic.replies.size
+ assert_equal 1, topic.reload.replies.size
+ end
+
+ def test_counter_cache_updates_in_memory_after_create
+ topic = Topic.create title: "Zoom-zoom-zoom"
+
+ topic.replies.create!(title: "re: zoom", content: "speedy quick!")
+ assert_equal 1, topic.replies_count
+ assert_equal 1, topic.replies.size
+ assert_equal 1, topic.reload.replies.size
+ end
+
+ def test_counter_cache_updates_in_memory_after_create_with_array
+ topic = Topic.create title: "Zoom-zoom-zoom"
+
+ topic.replies.create!([
+ { title: "re: zoom", content: "speedy quick!" },
+ { title: "re: zoom 2", content: "OMG lol!" },
+ ])
+ assert_equal 2, topic.replies_count
+ assert_equal 2, topic.replies.size
+ assert_equal 2, topic.reload.replies.size
+ end
+
def test_pushing_association_updates_counter_cache
topic = Topic.order("id ASC").first
reply = Reply.create!