Skip to content
This repository
Browse code

Fix exception if old and new targets are both nil. Fixes #1471.

Conflicts:

	activerecord/test/models/comment.rb
  • Loading branch information...
commit 5c591e5c969aaafa4053982064dcd3168bae5b2c 1 parent 15438c4
Jon Leighton authored July 12, 2011
2  activerecord/lib/active_record/associations/belongs_to_association.rb
@@ -37,7 +37,7 @@ def update_counters(record)
37 37
         # Checks whether record is different to the current target, without loading it
38 38
         def different_target?(record)
39 39
           record.nil? && owner[reflection.foreign_key] ||
40  
-          record.id   != owner[reflection.foreign_key]
  40
+          record && record.id != owner[reflection.foreign_key]
41 41
         end
42 42
 
43 43
         def replace_keys(record)
9  activerecord/test/cases/associations/belongs_to_associations_test.rb
@@ -672,4 +672,13 @@ def test_should_set_foreign_key_on_create_association!
672 672
     firm = client.create_firm! :name => "baa"
673 673
     assert_equal firm.id, client.client_of
674 674
   end
  675
+
  676
+  def test_self_referential_belongs_to_with_counter_cache_assigning_nil
  677
+    comment = Comment.create! :post => posts(:thinking), :body => "fuu"
  678
+    comment.parent = nil
  679
+    comment.save!
  680
+
  681
+    assert_equal nil, comment.reload.parent
  682
+    assert_equal 0, comments(:greetings).reload.children_count
  683
+  end
675 684
 end
3  activerecord/test/models/comment.rb
@@ -10,6 +10,9 @@ class Comment < ActiveRecord::Base
10 10
   belongs_to :post, :counter_cache => true
11 11
   has_many :ratings
12 12
 
  13
+  has_many :children, :class_name => 'Comment', :foreign_key => :parent_id
  14
+  belongs_to :parent, :class_name => 'Comment', :counter_cache => :children_count
  15
+
13 16
   def self.what_are_you
14 17
     'a comment...'
15 18
   end
1  activerecord/test/schema/schema.rb
@@ -155,6 +155,7 @@ def create_table(*args, &block)
155 155
     end
156 156
     t.string  :type
157 157
     t.integer :taggings_count, :default => 0
  158
+    t.integer :children_count, :default => 0
158 159
   end
159 160
 
160 161
   create_table :companies, :force => true do |t|

0 notes on commit 5c591e5

Please sign in to comment.
Something went wrong with that request. Please try again.