In this seventh part of a multi-part series on the Action Pack library for Rails, you'll learn how to create a registration form using form helpers. This article is excerpted from chapter six of the book Beginning Rails: From Novice to Professional, written by Jeffery Allan Hardy, Cloves Carneiro Jr. and Hampton Catlin (Apress; ISBN: 1590596862).
Creating an Action Pack Registration Form (Page 1 of 2 )
Creating a Registration Form
Enough tire-kicking. Let’s add some real code to the newtemplate so you can see it in action. Thenewaction has a single purpose: to initialize and display the form for creating a new user. The actual creation of a newUserobject is the responsibility of theUsermodel (remember our discussions of the model back to Chapters 4 and 5), but it’s orchestrated by the controller. Moreover, it needs data (like a login and password), which it must procure from somewhere. We’re going to extract this information from HTML form elements, which we’ll place in the template and handle in the controller. Let’s design the form now. Editnew.rhtmlso that it looks like Listing 6-4.
We’re using form helpers here for each of our fields. Refresh your browser again, and you’ll see they function to produce a nicely formatted HTML form. Use your browser’s view source command to look at the HTML that was generated.
Here, you can see the generated HTML. Note the way in which Rails formats thename attribute of each form element:model[attribute]. This helps when it comes to parsing the parameters from the form, which you’ll see shortly. If you were to manually create your form elements (which you need to do sometimes), you could use this naming convention to make sure your form values are easy to parse in the controller. Most of the time, though, you’ll use form helpers when working with forms, especially when dealing with Active Record objects. Let’s spend some time discussing form helpers now.