Skip to content

Commit

Permalink
Fixing issue where a required validation on a bool field would fail i…
Browse files Browse the repository at this point in the history
…f the value was false. Fixes #457
  • Loading branch information
jwoertink committed Sep 14, 2020
1 parent b002ead commit 0516dbd
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 1 deletion.
33 changes: 33 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,17 @@ describe "Avram::SaveOperation" do
r.drafted_at.should eq drafted_at
end
end

it "updates with a record that has defaults" do
model = ModelWithDefaultValuesBox.create
params = Avram::Params.new({"greeting" => "Hi"})
OverrideDefaults.update(model, params) do |_operation, record|
record.should_not eq nil
r = record.not_nil!
r.greeting.should eq "Hi"
r.admin.should eq false
end
end
end
end

Expand Down Expand Up @@ -553,6 +572,20 @@ describe "Avram::SaveOperation" do
end
end
end

context "when the default is false, but the field is required" do
it "passes required validation as '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.errors.should eq({} of Symbol => Array(String))
r.nickname.should eq "falsey mcfalserson"
r.available_for_hire.should eq false
end
end
end
end

describe ".update!" do
Expand Down
4 changes: 4 additions & 0 deletions spec/support/boxes/model_with_default_values_box.cr
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
class ModelWithDefaultValuesBox < BaseBox
def initialize
end
end
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 0516dbd

Please sign in to comment.