Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix for collection blank detection #78

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 14 additions & 13 deletions lib/default_value_for.rb
Original file line number Diff line number Diff line change
Expand Up @@ -156,19 +156,7 @@ def set_default_values

connection_default_value_defined = new_record? && respond_to?("#{attribute}_changed?") && !__send__("#{attribute}_changed?")

attribute_blank = if attributes.has_key?(attribute)
column = self.class.columns_hash[attribute]
if column && column.type == :boolean
attributes[attribute].nil?
else
attributes[attribute].blank?
end
elsif respond_to?(attribute)
send(attribute).nil?
else
instance_variable_get("@#{attribute}").nil?
end
next unless connection_default_value_defined || attribute_blank
next unless connection_default_value_defined || attribute_blank?(attribute)

# allow explicitly setting nil through allow nil option
next if @initialization_attributes.is_a?(Hash) &&
Expand All @@ -189,6 +177,19 @@ def set_default_values
end
end
end

def attribute_blank?(attribute)
if attributes.key?(attribute)
column = self.class.columns_hash[attribute]
return attributes[attribute].nil? if column && column.type == :boolean
return attributes[attribute].blank?
end
if respond_to?(attribute)
return send(attribute).nil? if !!send(attribute) == send(attribute)
return send(attribute).blank?
end
instance_variable_get("@#{attribute}").nil?
end
end
end

Expand Down
9 changes: 9 additions & 0 deletions test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -370,6 +370,15 @@ def test_works_with_stored_attribute_accessors_when_initializing_value_that_does
assert_equal 'This is a bio', user.bio
end

def test_works_with_empty_active_record_relation
book = Book.create!
User.default_value_for :books do
[book]
end
user = User.create
assert_equal user.books, [book]
end

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