diff --git a/spec/save_operation_spec.cr b/spec/save_operation_spec.cr index 420a900f3..742606de8 100644 --- a/spec/save_operation_spec.cr +++ b/spec/save_operation_spec.cr @@ -16,6 +16,14 @@ private class SaveUser < User::SaveOperation end end +private class SaveUserWithFalseValueValidations < User::SaveOperation + permit_columns :nickname, :available_for_hire + + before_save do + validate_required nickname, available_for_hire + end +end + private class SaveLimitedUser < User::SaveOperation permit_columns :name end @@ -428,6 +436,13 @@ describe "Avram::SaveOperation" do r.drafted_at.should eq drafted_at end end + + it "updates with a record that has defaults" do + model = ModelWithDefaultValues::SaveOperation.create! + record = OverrideDefaults.update!(model, greeting: "Hi") + record.greeting.should eq "Hi" + record.admin.should eq false + end end end @@ -553,6 +568,20 @@ describe "Avram::SaveOperation" do end end end + + context "when the default is false and the field is required" do + it "is valid since 'false' is a valid Boolean value" do + user = UserBox.create &.nickname("oopsie").available_for_hire(false) + params = Avram::Params.new({"nickname" => "falsey mcfalserson"}) + SaveUserWithFalseValueValidations.update(user, params) do |operation, record| + record.should_not eq nil + r = record.not_nil! + operation.valid?.should be_true + r.nickname.should eq "falsey mcfalserson" + r.available_for_hire.should eq false + end + end + end end describe ".update!" do diff --git a/src/avram/save_operation.cr b/src/avram/save_operation.cr index cfe88525d..3622f0021 100644 --- a/src/avram/save_operation.cr +++ b/src/avram/save_operation.cr @@ -120,10 +120,13 @@ abstract class Avram::SaveOperation(T) < Avram::Operation end private def _{{ attribute[:name] }} + record_value = @record.try(&.{{ attribute[:name] }}) + value = record_value.nil? ? default_value_for_{{ attribute[:name] }} : record_value + @_{{ attribute[:name] }} ||= Avram::Attribute({{ attribute[:type] }}?).new( name: :{{ attribute[:name].id }}, param: permitted_params["{{ attribute[:name] }}"]?, - value: @record.try(&.{{ attribute[:name] }}) || default_value_for_{{ attribute[:name] }}, + value: value, param_key: self.class.param_key) end