Quick Tip: Form Partials

Posted by Curtis Miller Curtis Miller

Partials are a great way to keep your view code separated logically. Prior to Rails 2.1 if you wanted to reuse a form partial in, for example, a new and edit view, then you needed to pass the form into the partial somehow.

Given the following form partial:

views/users/_form.html.erb

<div>
  <%= form.label :name -%>
  <%= form.text_field :name -%>
</div>

Pre-Rails 2.1

You might consider passing the form in as a local, like so.

views/users/new.html.erb or views/users/edit.html.erb

<% form_for @user do |form| -%>
  <%= render :partial => 'form', :locals => { :form => form } -%>
<% end -%>

Rails 2.1

There's now a shortcut for this common method of rendering a form partial.

views/users/new.html.erb or views/users/edit.html.erb

<% form_for @user do |form| -%>
  <%= render :partial => form -%>
<% end -%>

Nice! Cleans things up a bit.



Velocity Labs

Need web application development, maintenance for your existing app, or a third party code review?

Velocity Labs can help.

Hire us!