Skip to content

Commit 02ef0da

Browse files
committed
Update value_for_field fallback logic.
Up until this point, the `value_for_field` method would always fall back to the default values if the field value was falsy. This change makes it slightly more explicit by only using the default values when creating a new edition.
1 parent 151d235 commit 02ef0da

2 files changed

Lines changed: 26 additions & 1 deletion

File tree

app/components/edition/details/fields/object_component.rb

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,9 @@ def errors_for_field(field)
1414
end
1515

1616
def value_for_field(field)
17-
value&.fetch(field.name, nil) || field.default_value
17+
field_value = value&.fetch(field.name, nil)
18+
return field.default_value if edition.document.is_new_block? && field_value.nil?
19+
20+
field_value
1821
end
1922
end

test/components/edition/details/fields/object_component_test.rb

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,13 +75,35 @@ class Edition::Details::Fields::ObjectComponentTest < BaseComponentTestClass
7575
]
7676
end
7777

78+
# Ensure this edition belongs to a document with exactly one edition so defaults are applied
79+
let(:edition) { create(:edition, :pension) }
80+
7881
it "renders the field with the default values" do
7982
render_inline(component)
8083

8184
assert_selector "input[name=\"edition[details][nested][label]\"][value=\"LABEL DEFAULT\"]"
8285
assert_selector "input[name=\"edition[details][nested][type]\"][value=\"TYPE DEFAULT\"]"
8386
assert_selector "input[name=\"edition[details][nested][email_address]\"][value=\"EMAIL DEFAULT\"]"
8487
end
88+
89+
describe "but real values are also present" do
90+
let(:form_value) do
91+
{
92+
"label" => "Real Label",
93+
"type" => "Real Type",
94+
"email_address" => "Real Email Address",
95+
}
96+
end
97+
98+
it "renders the real values instead of defaults" do
99+
render_inline(component)
100+
101+
assert_selector "input[name=\"edition[details][nested][label]\"][value=\"Real Label\"]"
102+
assert_selector "input[name=\"edition[details][nested][type]\"][value=\"Real Type\"]"
103+
# Email address has no real value, so it should use the default
104+
assert_selector "input[name=\"edition[details][nested][email_address]\"][value=\"Real Email Address\"]"
105+
end
106+
end
85107
end
86108

87109
describe "when errors are present for the object" do

0 commit comments

Comments
 (0)