Ruby On Rails Classroom image

Pooja  Negi / Student / Web Technology

To post your Question Join Classroom
Lesson Topics's No:-  |1 | 2 | 3|Last
Lessons:-Using form for

Using form for

Now that we have good failing tests for user signup, we’ll start getting them to pass by making a form for signing up users. We can accomplish this in Rails with the form_for helper method, which takes in an Active Record object and constructs a form using the object’s attributes. The result appears in Listing 7.17. (Readers familiar with Rails 2.x should note that form_for uses the ‘‘percent-equals’’ ERb syntax for inserting content; that is, where Rails 2.x used <% form for ... %>, Rails 3 uses <%= form for ... %> instead.)


Listing 7.17 A form to sign up new users.




Let’s break this down into pieces. The presence of the do keyword indicates that form_for takes a block with one variable, which we’ve called f for ‘‘form’’:

< % =  form for( @userdo  |f|  %>
< %  end  % >


As is usually the case with Rails helpers, we don’t need to know any details about the implementation, but what we do need to know is what the f object does: When called with a method corresponding to an HTML form element—such as a text field, radio button, or password field—it returns code for that element specifically designed to set an attribute of the @user object. In other words,  

<%=   f.label   :name   %>
<%=   f.text field   :name   %>


creates the HTML needed to make a labeled text field element appropriate for setting the name attribute of a User model. (We’ll take a look at the HTML itself in Section 7.2.3.)

To see this in action, we need to drill down and look at the actual HTML produced by this form, but here we have a problem: The page currently breaks, because we have not set the @user variable—like all undefined instance variables (Section 4.4.5), @user is currently nil. Appropriately, if you run your test suite at this point, you’ll see that the tests for the structure of the signup page from Listing 7.6 (i.e., the h1 and the title) now fail:

$  bundle  exec  rspec spec/requests/user pages spec.rb -e   "signup page"


Pooja   Negi

Skills    Ruby On Rails

Qualifications :- High School - SSN high school, College/University - HNBGU, College/University - SRHU,
Location :-Ranipokhari,Rishikesh,Uttarakhand,India
Description:- Student

  Students (0)