Skip to content

Commit

Permalink
Ensure belongs_to association with a counter cache in name spaced mod…
Browse files Browse the repository at this point in the history
…el works [#1678 state:resolved]

Signed-off-by: Pratik Naik <pratiknaik@gmail.com>
  • Loading branch information
adamcooper authored and lifo committed Mar 6, 2009
1 parent 984bc7a commit 3ca5a0f
Show file tree
Hide file tree
Showing 5 changed files with 31 additions and 4 deletions.
4 changes: 1 addition & 3 deletions activerecord/lib/active_record/associations.rb
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion activerecord/lib/active_record/reflection.rb
Expand Up @@ -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
Expand Down
Expand Up @@ -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")
Expand Down
6 changes: 6 additions & 0 deletions activerecord/test/models/reply.rb
Expand Up @@ -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
6 changes: 6 additions & 0 deletions activerecord/test/models/topic.rb
Expand Up @@ -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

0 comments on commit 3ca5a0f

Please sign in to comment.