提交 3ca5a0f9 编写于 作者: A Adam Cooper 提交者: Pratik Naik

Ensure belongs_to association with a counter cache in name spaced model works...

Ensure belongs_to association with a counter cache in name spaced model works [#1678 state:resolved]
Signed-off-by: NPratik Naik <pratiknaik@gmail.com>
上级 984bc7a6
......@@ -1003,9 +1003,7 @@ def belongs_to(association_id, options = {})
# Create the callbacks to update counter cache
if options[:counter_cache]
cache_column = options[:counter_cache] == true ?
"#{self.to_s.demodulize.underscore.pluralize}_count" :
options[:counter_cache]
cache_column = reflection.counter_cache_column
method_name = "belongs_to_counter_cache_after_create_for_#{reflection.name}".to_sym
define_method(method_name) do
......
......@@ -197,7 +197,7 @@ def association_foreign_key
def counter_cache_column
if options[:counter_cache] == true
"#{active_record.name.underscore.pluralize}_count"
"#{active_record.name.demodulize.underscore.pluralize}_count"
elsif options[:counter_cache]
options[:counter_cache]
end
......
......@@ -154,6 +154,23 @@ def test_belongs_to_counter_with_reassigning
assert_equal 0, Topic.find(t2.id).replies.size
end
def test_belongs_to_reassign_with_namespaced_models_and_counters
t1 = Web::Topic.create("title" => "t1")
t2 = Web::Topic.create("title" => "t2")
r1 = Web::Reply.new("title" => "r1", "content" => "r1")
r1.topic = t1
assert r1.save
assert_equal 1, Web::Topic.find(t1.id).replies.size
assert_equal 0, Web::Topic.find(t2.id).replies.size
r1.topic = Web::Topic.find(t2.id)
assert r1.save
assert_equal 0, Web::Topic.find(t1.id).replies.size
assert_equal 1, Web::Topic.find(t2.id).replies.size
end
def test_belongs_to_counter_after_save
topic = Topic.create!(:title => "monday night")
topic.replies.create!(:title => "re: monday night", :content => "football")
......
......@@ -37,3 +37,9 @@ def validate_on_update
class SillyReply < Reply
belongs_to :reply, :foreign_key => "parent_id", :counter_cache => :replies_count
end
module Web
class Reply < Web::Topic
belongs_to :topic, :foreign_key => "parent_id", :counter_cache => true, :class_name => 'Web::Topic'
end
end
\ No newline at end of file
......@@ -71,3 +71,9 @@ def after_initialize
end
end
end
module Web
class Topic < ActiveRecord::Base
has_many :replies, :dependent => :destroy, :foreign_key => "parent_id", :class_name => 'Web::Reply'
end
end
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册