Skip to Main Content
Learning Rails
book

Learning Rails

by Simon St. Laurent, Edd Dumbill
November 2008
Beginner content levelBeginner
448 pages
12h 25m
English
O'Reilly Media, Inc.
Content preview from Learning Rails

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> ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Rails 5

Learning Rails 5

J. Mark Locklear, Eric J Gruber, Barnabas Bulpett
Mastering Ruby Closures

Mastering Ruby Closures

Benjamin Tan Wei Hao
Ruby on Rails® Bible

Ruby on Rails® Bible

Timothy Fisher

Publisher Resources

ISBN: 9780596154943Supplemental ContentErrata