Skip to content

Commit 4544b0d

Browse files
authored
Merge pull request rails#49943 from cjilbert504/handle-nil-form-model-object
Handle nil form_with model argument
2 parents 4a4d70b + 12b093d commit 4544b0d

File tree

3 files changed

+16
-2
lines changed

3 files changed

+16
-2
lines changed

actionview/CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
* Raise `ArgumentError` when `nil` is passed as `model:` argument value to the `form_with` method.
2+
3+
*Collin Jilbert*
4+
15
* Alias `field_set_tag` helper to `fieldset_tag` to match `<fieldset>` element
26

37
*Sean Doyle*

actionview/lib/action_view/helpers/form_helper.rb

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -437,7 +437,7 @@ def form_for(record, options = {}, &block)
437437

438438
case record
439439
when String, Symbol
440-
model = nil
440+
model = false
441441
object_name = record
442442
else
443443
model = record
@@ -753,7 +753,9 @@ def apply_form_for_options!(object, options) # :nodoc:
753753
# def labelled_form_with(**options, &block)
754754
# form_with(**options.merge(builder: LabellingFormBuilder), &block)
755755
# end
756-
def form_with(model: nil, scope: nil, url: nil, format: nil, **options, &block)
756+
def form_with(model: false, scope: nil, url: nil, format: nil, **options, &block)
757+
raise ArgumentError, "The :model argument cannot be nil" if model.nil?
758+
757759
options = { allow_method_names_outside_object: true, skip_default_ids: !form_with_generates_ids }.merge!(options)
758760

759761
if model

actionview/test/template/form_helper/form_with_test.rb

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -339,6 +339,14 @@ def url_for(object)
339339
super
340340
end
341341

342+
def test_form_with_when_given_nil_model_argument
343+
error = assert_raises(ArgumentError) do
344+
form_with(model: nil) do
345+
end
346+
end
347+
assert_equal "The :model argument cannot be nil", error.message
348+
end
349+
342350
def test_form_with
343351
form_with(model: @post, id: "create-post") do |f|
344352
concat f.label(:title) { "The Title" }

0 commit comments

Comments
 (0)