Skip to content

Commit 2ab9ff5

Browse files
committed
Merge branch 'acapilleri-update_nested_attributes'
Closes rails#6675
2 parents 69f19b2 + 17ce0b1 commit 2ab9ff5

File tree

2 files changed

+25
-5
lines changed

2 files changed

+25
-5
lines changed

activerecord/lib/active_record/attribute_methods/dirty.rb

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -77,11 +77,8 @@ def update(*)
7777

7878
def _field_changed?(attr, old, value)
7979
if column = column_for_attribute(attr)
80-
if column.number? && column.null && (old.nil? || old == 0) && value.blank?
81-
# For nullable numeric columns, NULL gets stored in database for blank (i.e. '') values.
82-
# Hence we don't record it as a change if the value changes from nil to ''.
83-
# If an old value of 0 is set to '' we want this to get changed to nil as otherwise it'll
84-
# be typecast back to 0 (''.to_i => 0)
80+
if column.number? && (changes_from_nil_to_empty_string?(column, old, value) ||
81+
changes_from_zero_to_string?(column, old, value))
8582
value = nil
8683
else
8784
value = column.type_cast(value)
@@ -90,6 +87,19 @@ def _field_changed?(attr, old, value)
9087

9188
old != value
9289
end
90+
91+
def changes_from_nil_to_empty_string?(column, old, value)
92+
# For nullable numeric columns, NULL gets stored in database for blank (i.e. '') values.
93+
# Hence we don't record it as a change if the value changes from nil to ''.
94+
# If an old value of 0 is set to '' we want this to get changed to nil as otherwise it'll
95+
# be typecast back to 0 (''.to_i => 0)
96+
column.null && (old.nil? || old == 0) && value.blank?
97+
end
98+
99+
def changes_from_zero_to_string?(column, old, value)
100+
# For columns with old 0 and value non-empty string
101+
old == 0 && value.present? && value != '0'
102+
end
93103
end
94104
end
95105
end

activerecord/test/cases/nested_attributes_test.rb

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -781,6 +781,16 @@ def test_can_use_symbols_as_object_identifier
781781
assert_nothing_raised(NoMethodError) { @pirate.save! }
782782
end
783783

784+
def test_numeric_colum_changes_from_zero_to_no_empty_string
785+
Man.accepts_nested_attributes_for(:interests)
786+
Interest.validates_numericality_of(:zine_id)
787+
man = Man.create(:name => 'John')
788+
interest = man.interests.create(:topic=>'bar',:zine_id => 0)
789+
assert interest.save
790+
791+
assert !man.update_attributes({:interests_attributes => { :id => interest.id, :zine_id => 'foo' }})
792+
end
793+
784794
private
785795

786796
def association_setter

0 commit comments

Comments
 (0)