method

form_for

form_for(record, options = {}, &block)
public

Creates a form that allows the user to create or update the attributes of a specific model object.

The method can be used in several slightly different ways, depending on how much you wish to rely on Rails to infer automatically from the model how the form should be constructed. For a generic model object, a form can be created by passing form_for a string or symbol representing the object we are concerned with:

<%= form_for :person do |f| %>
  First name: <%= f.text_field :first_name %><br />
  Last name : <%= f.text_field :last_name %><br />
  Biography : <%= f.textarea :biography %><br />
  Admin?    : <%= f.checkbox :admin %><br />
  <%= f.submit %>
<% end %>

The variable f yielded to the block is a FormBuilder object that incorporates the knowledge about the model object represented by :person passed to form_for. Methods defined on the FormBuilder are used to generate fields bound to this model. Thus, for example,

<%= f.text_field :first_name %>

will get expanded to

<%= text_field :person, :first_name %>

which results in an HTML <input> tag whose name attribute is person[first_name]. This means that when the form is submitted, the value entered by the user will be available in the controller as params[:person][:first_name].

For fields generated in this way using the FormBuilder, if :person also happens to be the name of an instance variable @person, the default value of the field shown when the form is initially displayed (e.g. in the situation where you are editing an existing record) will be the value of the corresponding attribute of @person.

The rightmost argument to form_for is an optional hash of options -

  • :url - The URL the form is to be submitted to. This may be represented in the same way as values passed to url_for or link_to. So for example you may use a named route directly. When the model is represented by a string or symbol, as in the example above, if the :url option is not specified, by default the form will be sent back to the current URL (We will describe below an alternative resource-oriented usage of form_for in which the URL does not need to be specified explicitly).

  • :namespace - A namespace for your form to ensure uniqueness of id attributes on form elements. The namespace attribute will be prefixed with underscore on the generated HTML id.

  • :method - The method to use when submitting the form, usually either “get” or “post”. If “patch”, “put”, “delete”, or another verb is used, a hidden input with name _method is added to simulate the verb over post.

  • :authenticity_token - Authenticity token to use in the form. Use only if you need to pass custom authenticity token string, or to not add authenticity_token field at all (by passing false). Remote forms may omit the embedded authenticity token by setting config.action_view.embed_authenticity_token_in_remote_forms = false. This is helpful when you’re fragment-caching the form. Remote forms get the authenticity token from the meta tag, so embedding is unnecessary unless you support browsers without JavaScript.

  • :remote - If set to true, will allow the Unobtrusive JavaScript drivers to control the submit behavior.

  • :enforce_utf8 - If set to false, a hidden input with name utf8 is not output.

  • :html - Optional HTML attributes for the form tag.

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. For example:

<%= form_for :person do |f| %>
  First name: <%= f.text_field :first_name %>
  Last name : <%= f.text_field :last_name %>
  Biography : <%= textarea :person, :biography %>
  Admin?    : <%= checkbox_tag "person[admin]", "1", @person.company.admin? %>
  <%= f.submit %>
<% end %>

This also works for the methods in FormOptionsHelper and DateHelper that are designed to work with an object as base, like FormOptionsHelper#collection_select and DateHelper#datetime_select.

form_for with a model object

In the examples above, the object to be created or edited was represented by a symbol passed to form_for, and we noted that a string can also be used equivalently. It is also possible, however, to pass a model object itself to form_for. For example, if @article is an existing record you wish to edit, you can create the form using

<%= form_for @article do |f| %>
  ...
<% end %>

This behaves in almost the same way as outlined previously, with a couple of small exceptions. First, the prefix used to name the input elements within the form (hence the key that denotes them in the params hash) is actually derived from the object’s class, e.g. params[:article] if the object’s class is Article. However, this can be overwritten using the :as option, e.g. -

<%= form_for(@person, as: :client) do |f| %>
  ...
<% end %>

would result in params[:client].

Secondly, the field values shown when the form is initially displayed are taken from the attributes of the object passed to form_for, regardless of whether the object is an instance variable. So, for example, if we had a local variable article representing an existing record,

<%= form_for article do |f| %>
  ...
<% end %>

would produce a form with fields whose initial state reflect the current values of the attributes of article.

Resource-oriented style

In the examples just shown, although not indicated explicitly, we still need to use the :url option in order to specify where the form is going to be sent. However, further simplification is possible if the record passed to form_for is a resource, i.e. it corresponds to a set of RESTful routes, e.g. defined using the resources method in config/routes.rb. In this case Rails will simply infer the appropriate URL from the record itself. For example,

<%= form_for @article do |f| %>
  ...
<% end %>

is then equivalent to something like:

<%= form_for @article, as: :article, url: article_path(@article), method: :patch, html: { class: "edit_article", id: "edit_article_45" } do |f| %>
  ...
<% end %>

And for a new record

<%= form_for(Article.new) do |f| %>
  ...
<% end %>

is equivalent to something like:

<%= form_for @article, as: :article, url: articles_path, html: { class: "new_article", id: "new_article" } do |f| %>
  ...
<% end %>

However you can still overwrite individual conventions, such as:

<%= form_for(@article, url: super_articles_path) do |f| %>
  ...
<% end %>

You can omit the action attribute by passing url: false:

<%= form_for(@article, url: false) do |f| %>
  ...
<% end %>

You can also set the answer format, like this:

<%= form_for(@article, format: :json) do |f| %>
  ...
<% end %>

For namespaced routes, like admin_article_url:

<%= form_for([:admin, @article]) do |f| %>
 ...
<% end %>

If your resource has associations defined, for example, you want to add comments to the document given that the routes are set correctly:

<%= form_for([@document, @comment]) do |f| %>
 ...
<% end %>

Where @document = Document.find(params[:id]) and @comment = Comment.new.

Setting the method

You can force the form to use the full array of HTTP verbs by setting

method: (:get|:post|:patch|:put|:delete)

in the options hash. If the verb is not GET or POST, which are natively supported by HTML forms, the form will be set to POST and a hidden input called _method will carry the intended verb for the server to interpret.

Unobtrusive JavaScript

Specifying:

remote: true

in the options hash creates a form that will allow the unobtrusive JavaScript drivers to modify its behavior. The form submission will work just like a regular submission as viewed by the receiving side (all elements available in params).

Example:

<%= form_for(@article, remote: true) do |f| %>
  ...
<% end %>

The HTML generated for this would be:

<form action='http://www.example.com' method='post' data-remote='true'>
  <input name='_method' type='hidden' value='patch' />
  ...
</form>

Setting HTML options

You can set data attributes directly by passing in a data hash, but all other HTML options must be wrapped in the HTML key. Example:

<%= form_for(@article, data: { behavior: "autosave" }, html: { name: "go" }) do |f| %>
  ...
<% end %>

The HTML generated for this would be:

<form action='http://www.example.com' method='post' data-behavior='autosave' name='go'>
  <input name='_method' type='hidden' value='patch' />
  ...
</form>

Removing hidden model id’s

The form_for method automatically includes the model id as a hidden field in the form. This is used to maintain the correlation between the form data and its associated model. Some ORM systems do not use IDs on nested models so in this case you want to be able to disable the hidden id.

In the following example the Article model has many Comments stored within it in a NoSQL database, thus there is no primary key for comments.

Example:

<%= form_for(@article) do |f| %>
  <%= f.fields_for(:comments, include_id: false) do |cf| %>
    ...
  <% end %>
<% end %>

Customized form builders

You can also build forms using a customized FormBuilder class. Subclass FormBuilder and override or define some more helpers, then use your custom builder. For example, let’s say you made a helper to automatically add labels to form inputs.

<%= form_for @person, url: { action: "create" }, builder: LabellingFormBuilder do |f| %>
  <%= f.text_field :first_name %>
  <%= f.text_field :last_name %>
  <%= f.textarea :biography %>
  <%= f.checkbox :admin %>
  <%= f.submit %>
<% end %>

In this case, if you use this:

<%= render f %>

The rendered template is people/_labelling_form and the local variable referencing the form builder is called labelling_form.

The custom FormBuilder class is automatically merged with the options of a nested fields_for call, unless it’s explicitly set.

In many cases you will want to wrap the above in another helper, so you could do something like the following:

def labelled_form_for(record_or_name_or_array, *args, &block)
  options = args.extract_options!
  form_for(record_or_name_or_array, *(args << options.merge(builder: LabellingFormBuilder)), &block)
end

If you don’t need to attach a form to a model instance, then check out FormTagHelper#form_tag.

Form to external resources

When you build forms to external resources sometimes you need to set an authenticity token or just render a form without it, for example when you submit data to a payment gateway number and types of fields could be limited.

To set an authenticity token you need to pass an :authenticity_token parameter

<%= form_for @invoice, url: external_url, authenticity_token: 'external_token' do |f| %>
  ...
<% end %>

If you don’t want to an authenticity token field be rendered at all just pass false:

<%= form_for @invoice, url: external_url, authenticity_token: false do |f| %>
  ...
<% end %>

12Notes

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| %>

Getting the object in a partial

tekwiz · Jan 27, 20095 thanks

If you need to get the object for the form inside a partial, and can't use the instance variable, use the #object method... This is particularly useful when you're dealing with single-table inheritance subclasses (e.g. MyOtherClass inherits from MyClass) or when you are using the same partial across different controllers.

==== new.html.erb

<% form_for(@my_object) do %>
<%= render :partial => 'form' %>
<%= submit_tag 'Create' %>
<% end %>

==== _form.html.erb

<% if f.object.class.is_a? MyClass %>

<%# do something... %> <% elsif f.object.is_a? MyOtherClass %> <%# do something else... %> <% 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))

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)