Skip to content

Commit 983ca6a

Browse files
author
Reuben Pereira
committed
Do not overwrite the database default value
When a new database record has a column that is set to its database default value, the "#{attribute}_changed?" method returns false, which causes default_value_for to overwrite the database default. This commit changes this behavior to not overwrite when the column is being set by the initialization attributes.
1 parent 0e96e64 commit 983ca6a

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

lib/default_value_for.rb

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,20 @@ def set_default_values
171171
end
172172
next unless connection_default_value_defined || attribute_blank
173173

174+
attribute_init_value_defined = @initialization_attributes.is_a?(Hash) &&
175+
(
176+
(
177+
@initialization_attributes.has_key?(attribute) &&
178+
@initialization_attributes[attribute].present?
179+
) ||
180+
(
181+
@initialization_attributes.has_key?("#{attribute}_attributes") &&
182+
nested_attributes_options.stringify_keys[attribute].present?
183+
)
184+
)
185+
186+
next if attribute_init_value_defined
187+
174188
# allow explicitly setting nil through allow nil option
175189
next if @initialization_attributes.is_a?(Hash) &&
176190
(

test.rb

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,11 @@ def test_overwrites_db_default
168168
assert_equal 1234, Book.new.count
169169
end
170170

171+
def test_does_not_overwrite_db_default_if_provided_by_mass_assignment
172+
Book.default_value_for(:count, :allows_nil => false) { 1234 }
173+
assert_equal Book.column_defaults['count'], Book.new(count: Book.column_defaults['count']).count
174+
end
175+
171176
def test_doesnt_overwrite_values_provided_by_mass_assignment
172177
Book.default_value_for :number, 1234
173178
assert_equal 1, Book.new(:number => 1, :count => 2).number
@@ -199,6 +204,11 @@ def test_overwrites_explicitly_provided_nil_values_in_mass_assignment
199204
assert_equal 1234, Book.new(:number => nil).number
200205
end
201206

207+
def test_overwrites_string_blank_value_in_mass_assignment
208+
Book.default_value_for(:type, :allows_nil => false) { 'string' }
209+
assert_equal 'string', Book.new(type: '').type
210+
end
211+
202212
def test_default_values_are_inherited
203213
Book.default_value_for :number, 1234
204214
assert_equal 1234, Novel.new.number

0 commit comments

Comments
 (0)