form_for
form_for(record, options = {}, &proc)
public
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 /> <%= f.submit %> <% 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 do |f| %> 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 /> <%= f.submit %> <% end %>
There, the argument is a symbol or string with the name of the object the form is about.
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 %>
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.
-
: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.
-
: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 : <%= text_area :person, :biography %> Admin? : <%= check_box_tag "person[admin]", @person.company.admin? %> <%= f.submit %> <% 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, :as => :post, :url => post_path(@post), :method => :put, :html => { :class => "edit_post", :id => "edit_post_45" } do |f| %> ... <% end %>
And for new records
<%= form_for(Post.new) do |f| %> ... <% end %>
is equivalent to something like:
<%= form_for @post, :as => :post, :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_posts_path) do |f| %> ... <% end %>
You can also set the answer format, like this:
<%= form_for(@post, :format => :json) do |f| %> ... <% end %>
If you have an object that needs to be represented as a different parameter, like a Person that acts as a Client:
<%= form_for(@person, :as => :client) do |f| %> ... <% end %>
For namespaced routes, like admin_post_url:
<%= form_for([:admin, @post]) 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|: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 expected default behavior is an XMLHttpRequest in the background instead of the regular POST arrangement, but ultimately the behavior is the choice of the JavaScript driver implementor. Even though it’s using JavaScript to serialize the form elements, the form submission will work just like a regular submission as viewed by the receiving side (all elements available in params).
Example:
<%= form_for(@post, :remote => true) do |f| %> ... <% end %>
The HTML generated for this would be:
<form action='http://www.example.com' method='post' data-remote='true'> <div style='margin:0;padding:0;display:inline'> <input name='_method' type='hidden' value='put' /> </div> ... </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 Post model has many Comments stored within it in a NoSQL database, thus there is no primary key for comments.
Example:
<%= form_for(@post) 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.text_area :biography %> <%= f.check_box :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, &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.
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 %>
Nested resources in form_for
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
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
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 %>
Compare old and new form for
Old form for
<% form_for :user, :url => users_path do %> <%= render :partial => 'form' %> <%= submit_tag 'Create' %> <% end %>
New form for
<% form_for(@user) do |f| %> <%= render :partial => f %> <%= submit_tag 'Create' %> <% end %>
Seriously! Do not forget the brackets
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 %>
has_one Nesting in Rails 2.0
Routers:
map.resources :user, :has_one => [:avatar]
Views:
form_for [@user, @avatar], :url => user_avatar_url(@user) do |f| ... end
Adding to the URL
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')
params hash gets the model id automatically
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"=>{...}} }
The :method goes in the :html option
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| -%>
:url conflicts with :format
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)
form_for with namescope and polymorphic path
<%= form_for([:namescope_name, @object], :url => polymorphic_path([:namescope_name, @objectable, @object])) do |form| %>
for the routes.
namescope :admin do
resources :articles do resources :comments end resources :photos do resources :comments end
end
<%= form_for([:admin, @comment], :url => polymorphic_path([:admin, @commentable, @comment])) do |form| %>
Note : @commentable = find_commentable
authenticity_token
<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
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
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
Similar to danwich’s note, 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)