Skip to content

Commit

Permalink
Fixing issue with required bool fields (#461)
Browse files Browse the repository at this point in the history
* Fixing issue where a required validation on a bool field would fail if the value was false. Fixes #457

* applying spec cleanup changes

* Removing this box since it's not actually needed for anything
  • Loading branch information
jwoertink committed Sep 18, 2020
1 parent 18fc522 commit a8651a9
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
29 changes: 29 additions & 0 deletions spec/save_operation_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down
5 changes: 4 additions & 1 deletion src/avram/save_operation.cr
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down

0 comments on commit a8651a9

Please sign in to comment.