Permalink
Browse files

Make sure that belongs_to counter decrements when assigning nil Closes

…#10804 [jeanmartin]

git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@8735 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
  • Loading branch information...
1 parent 02625c9 commit c48f744400844e4c73eb91c83d86c3e915a9d78b @NZKoz NZKoz committed Jan 26, 2008
@@ -13,7 +13,7 @@ def replace(record)
counter_cache_name = @reflection.counter_cache_column
if record.nil?
- if counter_cache_name && @owner[counter_cache_name] && !@owner.new_record?
+ if counter_cache_name && !@owner.new_record?
@reflection.klass.decrement_counter(counter_cache_name, @owner[@reflection.primary_key_name]) if @owner[@reflection.primary_key_name]
end
@@ -1308,6 +1308,18 @@ def test_belongs_to_counter
assert_equal 0, Topic.find(debate.id).send(:read_attribute, "replies_count"), "First reply deleted"
end
+ def test_belongs_to_counter_with_assigning_nil
+ p = Post.find(1)
+ c = Comment.find(1)
+
+ assert_equal p.id, c.post_id
+ assert_equal 2, Post.find(p.id).comments.size
+
+ c.post = nil
+
+ assert_equal 1, Post.find(p.id).comments.size
+ end
+
def test_belongs_to_counter_with_reassigning
t1 = Topic.create("title" => "t1")
t2 = Topic.create("title" => "t2")
@@ -877,7 +877,7 @@ def test_mass_assignment_protection_inheritance
end
def test_readonly_attributes
- assert_equal Set.new([ 'title' ]), ReadonlyTitlePost.readonly_attributes
+ assert_equal Set.new([ 'title', 'comments_count' ]), ReadonlyTitlePost.readonly_attributes
post = ReadonlyTitlePost.create(:title => "cannot change this", :body => "changeable")
post.reload
@@ -3,6 +3,7 @@ welcome:
author_id: 1
title: Welcome to the weblog
body: Such a lovely day
+ comments_count: 2
type: Post
thinking:
@@ -1,5 +1,5 @@
class Comment < ActiveRecord::Base
- belongs_to :post
+ belongs_to :post, :counter_cache => true
def self.what_are_you
'a comment...'
@@ -20,4 +20,4 @@ class VerySpecialComment < Comment
def self.what_are_you
'a very special comment...'
end
-end
+end
@@ -154,6 +154,7 @@
t.string :title, :null => false
t.text :body, :null => false
t.string :type
+ t.integer :comments_count, :default => 0
end
create_table :projects, :force => true do |t|

0 comments on commit c48f744

Please sign in to comment.