diff options
author | Sean Griffin <sean@thoughtbot.com> | 2014-06-15 19:16:30 -0600 |
---|---|---|
committer | Sean Griffin <sean@thoughtbot.com> | 2014-06-16 09:40:16 -0600 |
commit | e6690d37204dbd7154d275df75d9d0f98f5d2526 (patch) | |
tree | e4485022f5f2e8e1c42581cf968184a9b50b07aa /activerecord/lib/active_record | |
parent | f59ed560ac68aad47e56b6b0442b0b855ae9951e (diff) | |
download | rails-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/lib/active_record')
-rw-r--r-- | activerecord/lib/active_record/associations/has_many_association.rb | 26 | ||||
-rw-r--r-- | activerecord/lib/active_record/associations/has_many_through_association.rb | 1 |
2 files changed, 26 insertions, 1 deletions
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 |