chapter 8.1
1. let's first make a branch for the sign up chapter:
git checkout -b signing-up
2. also reset the database:
rake db:reset
3. we already got two basic test for new action in users_controller_spec.rb test
describe "GET 'new'" do
it "should be successful" do
get :new
response.should be_success
end
it "should have the right title" do
get :new
response.should have_selector("title", :content => "Sign up")
end
end
next, we will make a for in the new.htm.erb file
we will use form_for helper method.
(in prior rails, it use <% form_for %>
but in rails 3, it use <%= form_for %)
4.
<h1>Sign up</h1>
<%= form_for(@user) do |f| %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :email %><br />
<%= f.text_field :email %>
</div>
<div class="field">
<%= f.label :password %><br />
<%= f.password_field :password %>
</div>
<div class="field">
<%= f.label :password_confirmation, "Confirmation" %><br />
<%= f.password_field :password_confirmation %>
</div>
<div class="actions">
<%= f.submit "Sign up" %>
</div>
<% end %>
a. the "do" indicates that form_for takes a block, which has one var, which we call f for form.
inside the form_for helper, f is an object that represents a form.
b. f.label
f.text_field
f.password_field
c. the created html is:
<div class="field">
<label for="user_password">Password</label><br />
<input id="user_password" name="user[password]" size="30" type="password" />
</div>
here, the key is the special name attr, "user[password]"
The name values allow rails to construct an init hash(via the params var.), this hash will be used to create user.
d. the second important element is the form tag itself.
rails create the form tag using the @user object.
because every ruby object knows its own class, rails figures out that @user is of class User,
moreover, since @user is a new user, rails knows to construct a form with post method.
<form action="/users" class="new_user" id="new_user" method="post">
here, the class and id are not very useful, what matters is the action and method attrs.
action tell rails the objective url, and post tell rails this is a post action, want to create a new user.
so the objective action is "create" in users controller.
e. then we can see the "authenticity token" field,
<input name="authenticity_token" type="hidden"
value="rB82sI7Qw5J9J1UMILG/VQL411vH5putR+JwlxLScMQ=" />
here rails uses a special unique value to avoid a particular kind of cross-site scription attack called a forgery.
happily, rails takes care of it for you, and the input tag is hidden.
f. look at the password confirmation part, the label text is different from the field name, so
f.label take a second param, "Confirmation"