Chapter 4 - Registering users

Introduction

Now that we've built the database back-end to store RailsSpace user information, it's time to make a registration page to collect it. This will involve all three parts of the MVC architecture. The registration view will be dynamically generated by embedded Ruby using a Rails function specialized for producing HTML forms to interact with models. Once the form is submitted, the controller will use the form data to create a User model object. What happens next depends on whether the user is valid according to the criteria that we set in Section 3.2 when creating the User model: Valid users will be saved, resulting in a successful registration, while invalid users will be sent by the controller back to the registration view, with error messages suitable for display in the browser.

Because it touches on so many parts of Rails, user registration is fairly complicated but highly instructive. Mastering registration will take you a long way toward understanding Rails and being able to use it to make practical applications.

Table of Contents

  • 4.1 A User controller 65
  • 4.2 User registration: The view 66
    • 4.2.1 The registration view: Appearance 66
    • 4.2.2 Understanding the registration view 70
    • 4.2.3 Registration form refinements 72
    • 4.2.4 Fun with forms—and debug 75
  • 4.3 User registration: The action 77
    • 4.3.1 Form error messages 82
    • 4.3.2 Flash 85
    • 4.3.3 The finished register function 88
    • 4.3.4 A hub stub 89
  • 4.4 Linking in Registration 90
    • 4.4.1 Helper files 92
  • 4.5 An example user 95

Source Code

Errata

As of the first printing, these are the known corrections:

  1. p. 79. logs/development.log should be log/development.log.
  2. p. 84. "User foobar created!" should be "User created!"
  3. p. 86. Listing 4.17 is missing the nav div. Listing 4.17 on this site is correct.
  4. p. 89. In the variable interpolation sidebar, the irb session should look like this:
    irb(main):001:0> title = "RailsSpace" 
    => "RailsSpace" 
    irb(main):002:0> "Welcome to #{title}!" 
    => "Welcome to RailsSpace!" 
    irb(main):003:0> 'Welcome to #{title}!' 
    => "Welcome to \#{title}!"
    

    In other words, the first and second instances of #title should have curly braces to give #{title}, while the third #title should also have a backslash at the front, giving \#{title}.