3

The form_with helper doesn't generate ids for form elements, and therefore doesn't generate for attributes either. This differs from the old form_tag and form_for helpers.

If you want to use form_with instead of the deprecated form_tag and form_for helpers, but you want ids to generate, you need to add this to your config:

config.action_view.form_with_generates_ids = true

id generation is useful in some cases because certain front-end things may require it. On top of that, it seems to me that not generating for attributes means that forms generated with form_with have less a11y.

I'm currently working in an older codebase where form element ids are required, and my knee-jerk reaction is to enable the above config setting so I can use form_with without having to manually set IDs for every element.

What is the reasoning for making form_with not generate ids by default? I'm concerned that I'm missing something here, since I assume there's a good reason for the decision.

David Gay
  • 1,094
  • 2
  • 16
  • 32

1 Answers1

5

From Rails 5.2 onwards, that actually is the default:

config.action_view.form_with_generates_ids = true

You can see it in the release notes, along with the commit that changed it. From the description of that commit:

When form_with was introduced we disabled the automatic generation of ids that was enabled in form_for. This usually is not an good idea since labels don't work when the input doesn't have an id and it made harder to test with Capybara. You can still disable the automatic generation of ids setting config.action_view.form_with_generates_ids to false.

Doesn't seem like you're missing anything :D

  • Ah, yikes, looks like my confusion was a consequence of my being used to modern Rails, but working on a codebase that was running old Rails. Thanks for clearing that up! – David Gay May 27 '21 at 16:52
  • Yeah, that's happened to me too! No worries – Laura Murphy-Clarkin May 28 '21 at 17:17
  • This does not seem to be the default for me in Rails 6.1. `form_with` does not generate input `id`s, unless I use `fields_for` within that form. Adding the config and setting it to `true` does add the ids! Somehow it's not obeying the default. – nimmolo Oct 08 '22 at 07:46
  • Note: it's possibly because this is an updated old Rails app. Still, there was no config for `form_with_generates_ids` present in the app anywhere; it didn't generate them without me adding the config. – nimmolo Oct 08 '22 at 07:59
  • 1
    @nimmolo check to see `config.load_defaults` in `config/application.rb` is set to `5.2 or greater`. These are the [default values](https://guides.rubyonrails.org/configuring.html). – haley Nov 30 '22 at 02:52
  • Aha, thanks @haley... I didn't know about that config! This app wasn't loading defaults for any version. – nimmolo Nov 30 '22 at 05:08