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 ebec9d4 commit 091e6f7
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 @@ -151,12 +151,12 @@ def update_with_dirty


def field_changed?(attr, old, value) def field_changed?(attr, old, value)
if column = column_for_attribute(attr) 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. # 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 ''. # 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 # 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) # be typecast back to 0 (''.to_i => 0)
value = nil if value.blank? value = nil
else else
value = column.type_cast(value) value = column.type_cast(value)
end end
Expand Down
12 changes: 12 additions & 0 deletions activerecord/test/cases/dirty_test.rb
Expand Up @@ -68,6 +68,18 @@ def test_nullable_integer_not_marked_as_changed_if_new_value_is_blank
end end
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 def test_zero_to_blank_marked_as_changed
pirate = Pirate.new pirate = Pirate.new
pirate.catchphrase = "Yarrrr, me hearties" pirate.catchphrase = "Yarrrr, me hearties"
Expand Down

0 comments on commit 091e6f7

Please sign in to comment.