19

Rails 5 has introduced new form helper method form_with.

How does it differs with form_for and when is it more appropriate to use?

Rajkaran Mishra
  • 4,532
  • 2
  • 36
  • 61

3 Answers3

23

This is really in preparation for rails 5.1 where only form_with should be used. It's meant to serve as a replacement for the two methods form_for and form_tag.

form_for and form_tag in Rails were very similar, both allowed you to create a form tag but the first one uses model’s attributes to build create or update form, while the second one simply creates an HTML form tag with the passed URL as action.

Kevin Brown
  • 12,602
  • 34
  • 95
  • 155
  • could you add a link to that quote? I didn't see it mentioned in https://guides.rubyonrails.org. – builder-7000 May 20 '20 at 05:25
  • That's because it's not a quote from rubyguides. :) I extracted that from the guides and just used blockquote for formatting. – Kevin Brown May 20 '20 at 15:43
  • 1
    Note that now with `form_with`, your labels won't automatically link up to your inputs like they did previously with `id`s being automatically added. For a label to properly pair up to an input field (with the `for` attribute) you now need to explicitly add the `id` attribute to the input. – stwr667 Aug 10 '20 at 08:00
13

Use form_with (more up-to-date)

  • form_with is the latest.
  • form_for and form_tag are obsolete.

Why is there a change?

See Kasper Timm Hansen's pull request - I cannot state it better than pull request itself:

form_tag and form_for serve very similar use cases. This PR unifies that usage such that form_with can output just the opening form tag akin to form_tag and can just work with a url, for instance.

This means you don't need to use form_tag if you don't have a model. You can use the form_with helper and it can still handle URLs.

Note Re: Ids and Classes: The Ruby 5.1 version of form_with, by default doesn't attach a class or id to the form. For Rails 5.2 and later, however, form_with WILL automatically generate ids based on the model, if present—basically the same id behavior as form_for, so you will NOT need to manually specify them anymore. (source)

BenKoshy
  • 33,477
  • 14
  • 111
  • 80
  • 1
    The last paragraph about default `id`s and `class`s is an important distinction! For a label to properly pair up to an input field (with the `for` attribute) you now need to explicitly add the `id` attribute to the input. – stwr667 Aug 10 '20 at 07:58
2

Existing answers are great. What I also found helpful were the first few paragraphs here. Basically:

form_tag and form_for are soft deprecated and they will be replaced by form_with in the future.

stevec
  • 41,291
  • 27
  • 223
  • 311