diff options
author | Tristan Gamilis <tristan@2suggestions.com.au> | 2015-04-07 17:50:32 +1000 |
---|---|---|
committer | Tristan Gamilis <tristan@2suggestions.com.au> | 2015-04-07 17:50:41 +1000 |
commit | e0cb21f5f767606ad3ecf2db33855d27aa9f083d (patch) | |
tree | 422ffc0969aad5e6a6b43372a29846276eec9f06 /activerecord/lib/active_record/associations/has_many_association.rb | |
parent | 693b333920fc2f5b74f157d46d531cd97b692006 (diff) | |
download | rails-e0cb21f5f767606ad3ecf2db33855d27aa9f083d.tar.gz rails-e0cb21f5f767606ad3ecf2db33855d27aa9f083d.tar.bz2 rails-e0cb21f5f767606ad3ecf2db33855d27aa9f083d.zip |
Require explicit counter_cache option for has_many
Previously has_many associations assumed a counter_cache was to be used
based on the presence of an appropriately named column. This is
inconsistent, since the inverse belongs_to association will not make
this assumption. See issues #19042 #8446.
This commit checks for the presence of the counter_cache key in the
options of either the has_many or belongs_to association as well as
ensuring that the *_count column is present.
Diffstat (limited to 'activerecord/lib/active_record/associations/has_many_association.rb')
-rw-r--r-- | activerecord/lib/active_record/associations/has_many_association.rb | 9 |
1 files changed, 8 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 ca27c9fdde..794eb9e183 100644 --- a/activerecord/lib/active_record/associations/has_many_association.rb +++ b/activerecord/lib/active_record/associations/has_many_association.rb @@ -80,8 +80,15 @@ module ActiveRecord [association_scope.limit_value, count].compact.min end + + # Returns whether a counter cache should be used for this association. + # + # The counter_cache option must be given on either the owner or inverse + # association, and the column must be present on the owner. def has_cached_counter?(reflection = reflection()) - owner.attribute_present?(cached_counter_attribute_name(reflection)) + if reflection.options[:counter_cache] || (inverse = inverse_which_updates_counter_cache(reflection)) && inverse.options[:counter_cache] + owner.attribute_present?(cached_counter_attribute_name(reflection)) + end end def cached_counter_attribute_name(reflection = reflection()) |