method

form_for

form_for(object_name, *args, &proc)
public

Creates a form and a scope around a specific model object, which is then used as a base for questioning about values for the fields. Examples:

  <% form_for :person, @person, :url => { :action => "update" } do |f| %>
    First name: <%= f.text_field :first_name %>
    Last name : <%= f.text_field :last_name %>
    Biography : <%= f.text_area :biography %>
    Admin?    : <%= f.check_box :admin %>
  <% end %>

Worth noting is that the form_for tag is called in a ERb evaluation block, not a ERb output block. So that’s <% %>, not <%= %>. Also worth noting is that the form_for yields a form_builder object, in this example as f, which emulates the API for the stand-alone FormHelper methods, but without the object name. So instead of text_field :person, :name, you get away with f.text_field :name.

That in itself is a modest increase in comfort. The big news is that form_for allows us to more easily escape the instance variable convention, so while the stand-alone approach would require text_field :person, :name, :object => person to work with local variables instead of instance ones, the form_for calls remain the same. You simply declare once with :person, person and all subsequent field calls save :person and :object => person.

Also note that form_for doesn’t create an exclusive scope. It’s still possible to use both the stand-alone FormHelper methods and methods from FormTagHelper. Example:

  <% form_for :person, @person, :url => { :action => "update" } do |f| %>
    First name: <%= f.text_field :first_name %>
    Last name : <%= f.text_field :last_name %>
    Biography : <%= text_area :person, :biography %>
    Admin?    : <%= check_box_tag "person[admin]", @person.company.admin? %>
  <% end %>

Note: This also works for the methods in FormOptionHelper and DateHelper that are designed to work with an object as base. Like collection_select and datetime_select.

Html attributes for the form tag can be given as :html => {…}. Example:

  <% form_for :person, @person, :html => {:id => 'person_form'} do |f| %>
    ...
  <% end %>

You can also build forms using a customized FormBuilder class. Subclass <a href="/rails/ActionView/Helpers/FormBuilder">FormBuilder</a> and override or define some more helpers, then use your custom builder like so:

  <% form_for :person, @person, :url => { :action => "update" }, :builder => LabellingFormBuilder do |f| %>
    <%= f.text_field :first_name %>
    <%= f.text_field :last_name %>
    <%= text_area :person, :biography %>
    <%= check_box_tag "person[admin]", @person.company.admin? %>
  <% end %>

In many cases you will want to wrap the above in another helper, such as:

  def labelled_form_for(name, object, options, &proc)
    form_for(name, object, options.merge(:builder => LabellingFormBuiler), &proc)
  end

13Notes

Nested resources in form_for

autonomous · Jul 22, 200819 thanks

If you like doing things RESTfully and have a model relationship like: Post_ has many Comments_

Then you can construct a form_for within your view to mirror this relationship when creating comments: form_for [@post, @comment] do |f| ... end

You also need to make sure your routes reflect this relationship: map.resources :post, :has_many => [:comments]

Multipart form

Vidmantas · Aug 5, 200817 thanks

Don't forget to add :multipart => true if you have file upload in your form.

<% form_for "user", :html => { :multipart => true } do |f| %>

has_one Nesting in Rails 2.0

ozeias · Sep 28, 20083 thanks

Routers: map.resources :user, :has_one => [:avatar]

Views: form_for [@user, @avatar], :url => user_avatar_url(@user) do |f| ... end

Seriously! Do not forget the brackets

tripdragon · Oct 8, 20083 thanks

thank you source jamesandre.ws

the form_for([:admin, @user]) must have the [] brackets to avoid errors like "Only get requests are allowed"

<% form_for([:admin, @user]) do |f| %> <%= render :partial => 'form' %> <%= submit_tag "Create" %> <% end %>

params hash gets the model id automatically

nachocab · Nov 2, 20082 thanks

The params hash gets automatically populated with the id of every model that gets passed to form_for. If we were creating a song inside an existing album: URL:/albums/209/songs/new form_for [@album, @song] do |f| ... f.submit "Add" end

The params hash would be:
params = {"commit"=>"Add", "authenticity_token"=>"...", "album_id"=>"209", "song"=>{"song_attributes"=>{...}} } So, in the songs_controller you could use this album_id in a before_filter: before_filter :find_album protected def find_album @album = Album.find(params[:album_id]) end If you only did this: form_for @song do |f|

You would get this params hash: params = {"commit"=>"Add", "authenticity_token"=>"...", "song"=>{"song_attributes"=>{...}} }

Using hidden tags

miknight · Nov 4, 20092 thanks

To use an tag, use the following syntax:

<% form_for(@post) do |f| %>
<%= f.hidden_field :user_id, { :value => user.id } %>
<% end %>

The :method goes in the :html option

jopotts · Apr 9, 20102 thanks

When using a restful form helper and you want to use a method other than POST, remember to put the :method in the :html option.

e.g. To send a DELETE request instead of the usual POST (with a nested resource thrown in for good measure) use:

<% form_for [@post, @comment], :html => { :method => :delete } do |f| -%>

Adding to the URL

Manfred · Oct 26, 20112 thanks

If you want to use polymorphic routing for your object but you also need to specify other stuff like an anchor, you can explicitly generate the polymorphic url with extra options:

form_for @candidate,
  :url => polymorphic_path(@candidate, :anchor => 'signup')

:url conflicts with :format

ssoroka · Jun 22, 20111 thank

If you are passing both :url and :format, url overwrites the use of format, so you'll need to pass it in the url like so:

form_for user, :url => user_path(@user, :format => :json)

authenticity_token

bebesuk · Jun 24, 2010
<div style="margin:0;padding:0"> 
<input name="authenticity_token" type="hidden" value="f755bb0ed134b76c432144748a6d4b7a7ddf2b71" /> 
</div> 

Helper generates a div element with a hidden input inside. This is a security feature of Rails called cross-site request forgery protection and form helpers generate it for every form whose action is not “get”.

form_for with :as routing

danwich · Jan 16, 2012

The following will not work if your post model is routed with the :as option: form_for(@post) Instead, use the helper with your custom name: form_for(@post, :url => edit_renamedpost_path(@post))

Adding Additional Parameters to form_for

kapitan-petko · Jun 25, 2012

If you want to add additional parameters to the form_for helper, but still want to use one form for both your "create" and your "update" actions, you can add the additional parameters to the :url option, but you need to omit the :controller and :action keys.

form_for(@user, :url => {:param1 => "value1", :param2 => "value2"}) do |f|

or

form_for([@post, @comment], :url => {:param1 => "value1", :param2 => "value2"}) do |f|

where param1 and param2 are not :controller or :action

form_for with :path route

liamkun · Mar 7, 2014

Similar to danwich's note[http://apidock.com/rails/ActionView/Helpers/FormHelper/form_for#1226-form-for-with-as-routing)], if you specify a route using the :path option

resource :posts, path: 'articles'

then the form_for tag must specify the :url option

form_for(@post), url: post_path(@post)