Skip to content

Commit 8953740

Browse files
committed
Fix behavior for missing attributes in submit/assign_form_params: set the attribute to its default value or nil
1 parent f8f48ba commit 8953740

File tree

2 files changed

+13
-1
lines changed

2 files changed

+13
-1
lines changed

lib/hyper_active_form/base.rb

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,8 @@ def perform
2828
def assign_form_attributes(params)
2929
params = ActionController::Parameters.new(params) unless params.is_a?(ActionController::Parameters)
3030
attribute_names.each do |attribute|
31-
public_send(:"#{attribute}=", params&.dig(attribute)) if params&.key?(attribute)
31+
default_value = self.class._default_attributes[attribute]&.value_before_type_cast
32+
public_send(:"#{attribute}=", params&.dig(attribute) || default_value)
3233
end
3334
end
3435

spec/hyper_active_form/base_spec.rb

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ def self.model_name
1212
Class.new(HyperActiveForm::Base) do
1313
attribute :name
1414
attribute :age
15+
attribute :hobbies, default: []
1516

1617
def self.model_name
1718
ActiveModel::Name.new(self, nil, "Dummy")
@@ -42,6 +43,16 @@ def perform
4243
end
4344
end
4445

46+
describe "#assign_form_attributes" do
47+
it "assigns attributes from params or defaults or nil" do
48+
form = dummy_class.new(name: "John", age: 20)
49+
form.assign_form_attributes(name: "Mike")
50+
expect(form.name).to eq("Mike")
51+
expect(form.age).to eq(nil)
52+
expect(form.hobbies).to eq([])
53+
end
54+
end
55+
4556
describe "#submit" do
4657
context "when the form is valid" do
4758
it "returns true and performs the form" do

0 commit comments

Comments
 (0)