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> ...
Get Learning Rails: Live Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.