instance method form_for

Ruby on Rails 2.3.18

Since v2.2.3

Available in: v2.2.3 v2.3.18 v3.0.20 v3.1.12 v3.2.22.5 v4.0.13 v4.1.16 v4.2.9 v5.2.8.1 v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

form_for(record_or_name_or_array, *args, &proc)

Creates a form and a scope around a specific model object that is used as a base for questioning about values for the fields.

Rails provides succinct resource-oriented form generation with form_for like this:

<% form_for @offer do |f| %>
  <%= f.label :version, 'Version' %>:
  <%= f.text_field :version %><br />
  <%= f.label :author, 'Author' %>:
  <%= f.text_field :author %><br />
<% end %>

There, form_for is able to generate the rest of RESTful form parameters based on introspection on the record, but to understand what it does we need to dig first into the alternative generic usage it is based upon.

Generic form_for

The generic way to call form_for yields a form builder around a model:

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

There, the first argument is a symbol or string with the name of the object the form is about, and also the name of the instance variable the object is stored in.

The form builder acts as a regular form helper that somehow carries the model. Thus, the idea is that

<%= f.text_field :first_name %>

gets expanded to

<%= text_field :person, :first_name %>

If the instance variable is not @person you can pass the actual record as the second argument:

<% form_for :person, person, :url => { :action => "update" } do |f| %>
  ...
<% end %>

In that case you can think

<%= f.text_field :first_name %>

gets expanded to

<%= text_field :person, :first_name, :object => person %>

You can even display error messages of the wrapped model this way:

<%= f.error_messages %>

In any of its variants, the rightmost argument to form_for is an optional hash of options:

  • :url - The URL the form is submitted to. It takes the same fields you pass to url_for or link_to. In particular you may pass here a named route directly as well. Defaults to the current action.

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

Worth noting is that the form_for tag is called in a ERb evaluation block, not an ERb output block. So that’s <% %>, not <%= %>.

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

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

Resource-oriented style

As we said above, in addition to manually configuring the form_for call, you can rely on automated resource identification, which will use the conventions and named routes of that approach. This is the preferred way to use form_for nowadays.

For example, if @post is an existing record you want to edit

<% form_for @post do |f| %>
  ...
<% end %>

is equivalent to something like:

<% form_for :post, @post, :url => post_path(@post), :html => { :method => :put, :class => "edit_post", :id => "edit_post_45" } do |f| %>
  ...
<% end %>

And for new records

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

expands to

<% form_for :post, Post.new, :url => posts_path, :html => { :class => "new_post", :id => "new_post" } do |f| %>
  ...
<% end %>

You can also overwrite the individual conventions, like this:

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

And for namespaced routes, like admin_post_url:

<% form_for([:admin, @post]) do |f| %>
 ...
<% 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, @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 this case, if you use this:

<%= render :partial => 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 explicitely 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, &proc)
  options = args.extract_options!
  form_for(record_or_name_or_array, *(args << options.merge(:builder => LabellingFormBuilder)), &proc)
end

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

Parameters

record_or_name_or_array req
args rest
proc block
Source
# File actionpack/lib/action_view/helpers/form_helper.rb, line 261
      def form_for(record_or_name_or_array, *args, &proc)
        raise ArgumentError, "Missing block" unless block_given?

        options = args.extract_options!

        case record_or_name_or_array
        when String, Symbol
          object_name = record_or_name_or_array
        when Array
          object = record_or_name_or_array.last
          object_name = ActionController::RecordIdentifier.singular_class_name(object)
          apply_form_for_options!(record_or_name_or_array, options)
          args.unshift object
        else
          object = record_or_name_or_array
          object_name = ActionController::RecordIdentifier.singular_class_name(object)
          apply_form_for_options!([object], options)
          args.unshift object
        end

        concat(form_tag(options.delete(:url) || {}, options.delete(:html) || {}))
        fields_for(object_name, *(args << options), &proc)
        concat('</form>'.html_safe)
      end

Defined in actionpack/lib/action_view/helpers/form_helper.rb line 261 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActionView::Helpers::FormHelper

Type at least 2 characters to search.

↑↓ navigate · open · esc close