Difference between form_for and form_tag?

旧时模样 提交于 2019-11-29 06:15:10

The differences are subtle, but important. form_for is a more advanced tool that yields an object you use to generate your form elements:

<% form_for(@foo) do |form| %>
  <%= form.text_field(:bar) %>
<% end %>

The form_tag method is much more primitive and just emits a tag. If you want to put things inside of the <form> tag that's emitted, you put things inside the block:

<% form_tag do %>
  <%= text_field_tag(:bar, 'bar_value') %>
<% end %>

Note that the form_for method handles grabbing values from your model, and will at least try to route the form to the appropriate action. With form_tag you are responsible for everything as it makes no assumptions about what you're doing.

One uses model binding and the other doesn't

As far as I know there is only one simple difference. form_tag without a block will only generate a html element for you. When you use form with a a block it will also create the form closing tag .

In example:

<% form_tag("/comments") %>

will result in

<form action="/comments">

Where

<%= form_tag("/comments") do %>
  <%= submit_tag %>
<% end %>

will generate

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