Rails Views: form_for

Posted 2006-05-27…

The whole thing is pretty simple.

<% form_for :student, @student,
      :url => student_url(:action=>'update') do |f| %>
  <ul>
    <li>Name: <%= f.text_field(:name) %></li>
    <li>Age: <%= f.text_field(:age,:size=>2) %></li>
  </ul>
  <%= submit_tag "Save" %>
<% end %>

Some observations:

There’s a lot more to talk about here, including fields_for and form builders (which are worth a post all by themselves), but I think you get the point.

Reference: form_helper.rb in a fresh edge rails checkout.

In the beginning (or nearly so), we had form_tag and end_form_tag. Now, these were still better than typing <form> and </form>, and trying to throw in form attributes, but they really didn’t even begin to use the full power of what Ruby (and ERB) had to offer.

A while back, form_for (and it’s sexy friend remote_form_for) came on the scene, but a lot of people haven’t noticed. These are cleaner, more elegant, and more flexible ways of making both regular and remote forms, and you should be using them.