Difference between form_for , form_tag?

Ruby on-Rails

Ruby on-Rails Problem Overview


What is the difference between form_for and form_tag? Is anything different for form_remote_for and form_remote_tag?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

You would use form_for for a specific model,

<% form_for @person do |f| %> # you can use f here

    First name: <%= f.text_field :first_name %>
    Last name : <%= f.text_field :last_name %>

<% end %>

Form_tag create basic form,

<%= form_tag '/person' do -%>
  <%= text_field_tag "person", "first_name" %>
<% end -%>

Solution 2 - Ruby on-Rails

form_for prefers, as its first arg, an activerecord object; it allows to easily make a create or edit form (to use it in a "new" view you should create an empty instance in controller, like:

def new
  @foo = Foo.new
end

It also passes a form variable to the block, so that you don't have to repeat the model name within the form itself. it's the preferred way to write a model related form.

form_tag just creates a form tag (and of course silently prepare an antiforgery hidden field, like form_for); it's best used for non-model forms (I actually only use it for simple search forms or the like).

Similarly, form_remote_for and form_remote_tag are suited for model related forms and not model related forms respectively but, instead of ending in a standard http method (GET, POST...), they call an ajax method.

All this and far more are available for you to enjoy in the [FormHelper][1] and [PrototypeHelper][2] reference pages.

EDIT 2012-07-13

Prototype has been removed from rails long ago, and remote forms have completely changed. Please refer to the first link, with reguard to the :remote option of both form_for and form_tag.

[1]: http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html "FormHelper reference" [2]: http://rails.rubyonrails.org/classes/ActionView/Helpers/PrototypeHelper.html

Solution 3 - Ruby on-Rails

These should be similar:

<% form_for @person do |f| %>
  <%= f.text_field :name %>
<% end %>

and:

<%= form_tag '/person' do %>
  <%= text_field_tag "person[name]" %>
<% end %>

If you want to submit the same params to the controller, you would have to define this explicitly.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondevinrossView Question on Stackoverflow
Solution 1 - Ruby on-Railsez.View Answer on Stackoverflow
Solution 2 - Ruby on-RailsgiorgianView Answer on Stackoverflow
Solution 3 - Ruby on-RailsMatthiasView Answer on Stackoverflow