From cbb253a56a44a49e500f1b6cfe0ba23bf03aa206 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Romain=20Durrit=C3=A7ague?= Date: Wed, 29 Aug 2018 17:17:20 +0200 Subject: [PATCH] Fix for collection blank detection --- lib/default_value_for.rb | 27 ++++++++++++++------------- test.rb | 9 +++++++++ 2 files changed, 23 insertions(+), 13 deletions(-) diff --git a/lib/default_value_for.rb b/lib/default_value_for.rb index ee042a4..c3a173f 100644 --- a/lib/default_value_for.rb +++ b/lib/default_value_for.rb @@ -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) && @@ -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 diff --git a/test.rb b/test.rb index f890c50..2d04fb8 100644 --- a/test.rb +++ b/test.rb @@ -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