From e6690d37204dbd7154d275df75d9d0f98f5d2526 Mon Sep 17 00:00:00 2001 From: Sean Griffin Date: Sun, 15 Jun 2014 19:16:30 -0600 Subject: 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. --- .../associations/has_many_association.rb | 26 ++++++++++++++++++++++ .../associations/has_many_through_association.rb | 1 - 2 files changed, 26 insertions(+), 1 deletion(-) (limited to 'activerecord/lib') diff --git a/activerecord/lib/active_record/associations/has_many_association.rb b/activerecord/lib/active_record/associations/has_many_association.rb index 2727e23870..477888228d 100644 --- a/activerecord/lib/active_record/associations/has_many_association.rb +++ b/activerecord/lib/active_record/associations/has_many_association.rb @@ -83,6 +83,13 @@ module ActiveRecord if has_cached_counter?(reflection) counter = cached_counter_attribute_name(reflection) owner.class.update_counters(owner.id, counter => difference) + update_counter_in_memory(difference, reflection) + end + end + + def update_counter_in_memory(difference, reflection = reflection()) + if has_cached_counter?(reflection) + counter = cached_counter_attribute_name(reflection) owner[counter] += difference owner.changed_attributes.delete(counter) # eww end @@ -137,6 +144,25 @@ module ActiveRecord false end end + + def concat_records(records, *) + update_counter_if_success(super, records.length) + end + + def _create_record(attributes, *) + if attributes.is_a?(Array) + super + else + update_counter_if_success(super, 1) + end + end + + def update_counter_if_success(saved_successfully, difference) + if saved_successfully + update_counter_in_memory(difference) + end + saved_successfully + end end end end diff --git a/activerecord/lib/active_record/associations/has_many_through_association.rb b/activerecord/lib/active_record/associations/has_many_through_association.rb index 175019a72b..00234dc8f4 100644 --- a/activerecord/lib/active_record/associations/has_many_through_association.rb +++ b/activerecord/lib/active_record/associations/has_many_through_association.rb @@ -63,7 +63,6 @@ module ActiveRecord end save_through_record(record) - update_counter(1) record end -- cgit v1.2.3