Add the form attribute to all form elements

I would like the Rails form helper methods to add the form attribute to each form element. The form attribute should have a value equal to the associated form’s id.

Why? I was building a page with multiple forms, one of which having inputs defined outside of the <form> (which is completely legal according to the spec, as long as you define the form attribute so the browser knows what form to associate the input with). I ran into the issue that the browser was picking up two different hidden _method input elements, each with a different value, causing Rails to route one of the forms the wrong controller action. By creating a custom form builder I could easily automatically add the form attribute to all elements created by the builder, but the hidden fields for _method and authenticity_token are not created by the form builder but by a helper function.

The changes necessary to do this are relatively simple. Just two questions: is this a good idea to add to rails, and if so, should the attribute be added by default or only activated with an option flag?

This doesn’t seem likely as a premise. A form will only submit its own contents. You can have two or ten forms on a page, and they can contain elements with the same names, but only the elements within the form that is submitted will be sent to the server. All the rest will not be part of the form parameters. A form may not contain another form, so there’s no way that they can become nested inside one another if the page is valid.

If I were debugging this unexpected result, I would start by using an HTML5 validator, like the one at https://validator.w3.org, to evaluate the source of this form page. Just visit your form in a browser on your computer, copy the page source (not the rendered DOM elements) and paste it into the validator. See if the result is valid. If it isn’t, work through the errors until you have a valid form. I suspect that your problem with Rails will go away at the same time.

Walter

1 Like

Thanks a lot, Walter, you are absolutely right! Looking further into the issue, I was using form_tag without a block which doesn’t add a closing form tag. The page renders without errors in all browsers, but the forms start to misbehave because it’s unclear which elements belong to which form.