O'Reilly logo

Learning Rails by Edd Dumbill, Simon St. Laurent

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Form As a Wrapper

The form_for helper method sets up the entire form, creating the HTML form element but also providing context for all of the fields in the form. The form_for method is a bit sneaky, too. Both the new.html.erb view and the edit.html.erb view use form_for the same way:

<% form_for(@person) do |f| %>
...
<% end %>

However, the generated form element looks very different, depending on what exactly is in @person. If @person is just an empty object structure, form_for will work on the assumption that this is to create a new object. If @person actually contains data, however, form_for will assume that its form is editing that object and create a different-looking form element, plus a hidden field to enable Rails’ REST capabilities.

When given an empty @person object, form_for prepares for a new person:

<form action="/people" class="new_person" id="new_person" method="post"><div
style="margin:0;padding:0"><input name="authenticity_token" type="hidden"
value="f80a01b9f14d38e0816877e832637e3cc9e668a1" /></div>

Note that the action goes to people, generically. The class and id reflect a new person, and the method is simply post.

When given an @person object with content, however, form_for switches to editing a person:

<form action="/people/1" class="edit_person" id="edit_person_1" method="post">
<div
style="margin:0;padding:0"><input name="_method" type="hidden" value="put" /><input name="authenticity_token" type="hidden" value="f80a01b9f14d38e0816877e832637e3cc9e668a1" /></div> ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required