Skip to content

Commit

Permalink
Change field_changed? method to handle the case where a nullable inte…
Browse files Browse the repository at this point in the history
…ger column is changed from 0 to '0'

[#1530 state:committed]

Signed-off-by: Jeremy Kemper <jeremy@bitsweat.net>
  • Loading branch information
bensymonds authored and jeremy committed Dec 8, 2008
1 parent a1fe469 commit 4130e13
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
4 changes: 2 additions & 2 deletions activerecord/lib/active_record/dirty.rb
Expand Up @@ -147,12 +147,12 @@ def update_with_dirty

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
Expand Down
12 changes: 12 additions & 0 deletions activerecord/test/cases/dirty_test.rb
Expand Up @@ -55,6 +55,18 @@ def test_nullable_integer_not_marked_as_changed_if_new_value_is_blank
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"
Expand Down

0 comments on commit 4130e13

Please sign in to comment.