Permalink
Browse files

Merge pull request #8116 from senny/7993_configure_counter_cache_for_…

…has_many

:counter_cache option for  to support custom named counter caches
  • Loading branch information...
2 parents edd94ce + 710e371 commit dbb39e53414294818c056f1db336471dd347d413 @jonleighton jonleighton committed Nov 9, 2012
@@ -1,5 +1,10 @@
## Rails 4.0.0 (unreleased) ##
+* :counter_cache option for `has_many` associations to support custom named counter caches.
+ Fix #7993
+
+ *Yves Senn*
+
* Deprecate the possibility to pass a string as third argument of `add_index`.
Pass `unique: true` instead.
@@ -1125,6 +1125,9 @@ module ClassMethods
# If using with the <tt>:through</tt> option, the association on the join model must be
# a +belongs_to+, and the records which get deleted are the join records, rather than
# the associated records.
+ # [:counter_cache]
+ # This option can be used to configure a custom named <tt>:counter_cache.</tt> You only need this option,
+ # when you customized the name of your <tt>:counter_cache</tt> on the <tt>belongs_to</tt> association.
# [:as]
# Specifies a polymorphic interface (See <tt>belongs_to</tt>).
# [:through]
@@ -5,7 +5,7 @@ def macro
end
def valid_options
- super + [:primary_key, :dependent, :as, :through, :source, :source_type, :inverse_of]
+ super + [:primary_key, :dependent, :as, :through, :source, :source_type, :inverse_of, :counter_cache]
end
def valid_dependent_options
@@ -76,7 +76,7 @@ def has_cached_counter?(reflection = reflection)
end
def cached_counter_attribute_name(reflection = reflection)
- "#{reflection.name}_count"
+ options[:counter_cache] || "#{reflection.name}_count"
end
def update_counter(difference, reflection = reflection)
@@ -754,6 +754,14 @@ def test_deleting_updates_counter_cache_with_dependent_destroy
end
end
+ def test_custom_named_counter_cache
+ topic = topics(:first)
+
+ assert_difference "topic.reload.replies_count", -1 do
+ topic.approved_replies.clear
+ end
+ end
+
def test_deleting_a_collection
force_signal37_to_load_all_clients_of_firm
companies(:first_firm).clients_of_firm.create("name" => "Another Client")
@@ -33,6 +33,7 @@ def two
end
has_many :replies, :dependent => :destroy, :foreign_key => "parent_id"
+ has_many :approved_replies, -> { approved }, class_name: 'Reply', foreign_key: "parent_id", counter_cache: 'replies_count'
has_many :replies_with_primary_key, :class_name => "Reply", :dependent => :destroy, :primary_key => "title", :foreign_key => "parent_title"
has_many :unique_replies, :dependent => :destroy, :foreign_key => "parent_id"

0 comments on commit dbb39e5

Please sign in to comment.