Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 5: form_for vs form_with

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?

like image 764
Rajkaran Mishra Avatar asked May 09 '17 11:05

Rajkaran Mishra


People also ask

What is the difference between Form_with and Form_for?

You use form_for with a model and form_tag for custom URLs. Both generate HTML for a form . There are only a few minor differences so Rails 5.1 combined the two. You should now be using form_with .

What is the difference between Form_for and form_tag?

form_for prefers the argument that you're passing in to be an active record object. This will easily make a create or edit form. We use form_for with a specific model and use form_tag when you don't have a model for it (for custom URLs). Both form_for and form_tag produce HTML for a form.


3 Answers

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.

like image 55
Kevin Brown Avatar answered Oct 16 '22 18:10

Kevin Brown


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)

like image 31
BenKoshy Avatar answered Oct 16 '22 19:10

BenKoshy


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.

  • DHH's proposal: https://github.com/rails/rails/issues/25197
  • The pull request: https://github.com/rails/rails/pull/26976/files (I didn't read it, but it could be useful)
like image 34
stevec Avatar answered Oct 16 '22 19:10

stevec