From 49f9ebf68ab24942a06d2f0b1d5ca9a37cd3373b Mon Sep 17 00:00:00 2001 From: Ben Symonds Date: Mon, 8 Dec 2008 14:11:55 +0000 Subject: [PATCH] Change field_changed? method to handle the case where a nullable integer column is changed from 0 to '0' --- activerecord/lib/active_record/dirty.rb | 4 ++-- activerecord/test/cases/dirty_test.rb | 12 ++++++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/activerecord/lib/active_record/dirty.rb b/activerecord/lib/active_record/dirty.rb index ae57379..a176087 100644 --- a/activerecord/lib/active_record/dirty.rb +++ b/activerecord/lib/active_record/dirty.rb @@ -151,12 +151,12 @@ module ActiveRecord def field_changed?(attr, old, value) if column = column_for_attribute(attr) - if column.type == :integer && column.null && (old.nil? || old == 0) + if column.type == :integer && column.null && (old.nil? || old == 0) && value.blank? # For nullable integer columns, NULL gets stored in database for blank (i.e. '') values. # Hence we don't record it as a change if the value changes from nil to ''. # If an old value of 0 is set to '' we want this to get changed to nil as otherwise it'll # be typecast back to 0 (''.to_i => 0) - value = nil if value.blank? + value = nil else value = column.type_cast(value) end diff --git a/activerecord/test/cases/dirty_test.rb b/activerecord/test/cases/dirty_test.rb index 39d38c4..10cdbdc 100644 --- a/activerecord/test/cases/dirty_test.rb +++ b/activerecord/test/cases/dirty_test.rb @@ -68,6 +68,18 @@ class DirtyTest < ActiveRecord::TestCase end end + def test_nullable_integer_zero_to_string_zero_not_marked_as_changed + pirate = Pirate.new + pirate.parrot_id = 0 + pirate.catchphrase = 'arrr' + assert pirate.save! + + assert !pirate.changed? + + pirate.parrot_id = '0' + assert !pirate.changed? + end + def test_zero_to_blank_marked_as_changed pirate = Pirate.new pirate.catchphrase = "Yarrrr, me hearties" -- 1.5.6.3