Skip to content

Commit

Permalink
Fix setting defaults for nested attributes
Browse files Browse the repository at this point in the history
Resolves #16
  • Loading branch information
norman committed Dec 15, 2014
1 parent 95abb59 commit 938b5a2
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
10 changes: 9 additions & 1 deletion lib/default_value_for.rb
Expand Up @@ -165,7 +165,15 @@ def set_default_values
next unless connection_default_value_defined || attribute_blank

# allow explicitly setting nil through allow nil option
next if @initialization_attributes.is_a?(Hash) && @initialization_attributes.has_key?(attribute) && !self.class._all_default_attribute_values_not_allowing_nil.include?(attribute)
next if @initialization_attributes.is_a?(Hash) &&
(
@initialization_attributes.has_key?(attribute) ||
(
@initialization_attributes.has_key?("#{attribute}_attributes") &&
nested_attributes_options.stringify_keys[attribute]
)
) &&
!self.class._all_default_attribute_values_not_allowing_nil.include?(attribute)

__send__("#{attribute}=", container.evaluate(self))
if self.class.private_instance_methods.include? :clear_attribute_changes
Expand Down
10 changes: 10 additions & 0 deletions test.rb
Expand Up @@ -343,6 +343,16 @@ def test_does_not_see_false_as_blank_at_boolean_columns_for_existing_records
assert_equal false, Book.find(object.id).flag
end

def test_works_with_nested_attributes
User.accepts_nested_attributes_for :books
User.default_value_for :books do
[Book.create!(:number => 0)]
end

user = User.create! :books_attributes => [{:number => 1}]
assert_equal 1, Book.all.first.number
end

if ActiveRecord::VERSION::MAJOR == 3
def test_constructor_ignores_forbidden_mass_assignment_attributes
Book.class_eval do
Expand Down

0 comments on commit 938b5a2

Please sign in to comment.