Rails 5: form_for vs form_with

烂漫一生 提交于 2021-02-08 12:33:30

问题


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?


回答1:


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.




回答2:


Use form_with (because it's more up-to-date)

form_with is the new kid on the block. form_for and form_tag are now (basically) obsolete.

Why is there a change?

The reasons are contained in Kasper Timm Hansen's pull request - I cannot say it better than what is stated already in the pull request itself (see the link for the pull request).

A direct quote from the pull request:

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.

form_with by default doesn't attach a class or id to the form.

The old helper methods (form_for) dictated to you ids and classes to add to your html. form_with makes no such assumptions. Sure, this means you will have to do a little more work to add in the ids and classes you want, but this also gives you full control.




回答3:


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)


来源:https://stackoverflow.com/questions/43868976/rails-5-form-for-vs-form-with

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!