Home>Articles

Sign Up

Allow users to sign up on your website, from collecting signup information with an HTML form and rendering a profile page, to validating users by adding a separate account activation step.

This chapter is from the book

Now that we have a working User model, it’s time to add an ability few websites can live without: letting users sign up. We’ll use an HTMLformto submit user signup information to our application (Section 7.2), which will then be used to create a new user and save its attributes to the database (Section 7.4). At the end of the signup process, it’s important to render a profile page with the newly created user’s information, so we’ll begin by making a page forshowingusers, which will serve as the first step toward implementing the REST architecture for users (Section 2.2.2). Along the way, we’ll build on our work in Section 5.3.4 to write succinct and expressive integration tests.

In this chapter, we’ll rely on the User model validations from Chapter 6 to increase the odds of new users having valid email addresses. In Chapter 11, we’ll makesureof email validity by adding a separateaccount activationstep to user signup.

Although this tutorial is designed to be as simple as possible while still being professional-grade, web development is a complicated subject, and Chapter 7 necessarily marks a significant increase in the difficulty of the exposition. I recommend taking your time with the material and reviewing it as necessary. (Some readers have reported simply doing the chapter twice is a helpful exercise.) You might also consider subscribing to the courses atLearn Enough(https://www.learnenough.com/) to gain additional assistance, both with this tutorial and with related Learn Enough titles (especiallyLearn Enough Ruby to Be Dangerous(https://www.learnenough.com/ruby)).

7.1 Showing Users

In this section, we’ll take the first steps toward the final profile by making a page to display a user’s name and profile photo, as indicated by the mockup in图7.1.1Our eventual goal for the user profile pages is to show the user’s profile image, basic user data, and a list of microposts, asmocked up in图7.2.2(图7.2includes an example oflorem ipsumtext, which has a fascinating story that you should definitely read about some time.) We’ll complete this task, and with it the sample application, in Chapter 14.

图7.1

图7.1:A mockup of the user profile made in this section.

If you’re following along with version control, make a topic branch as usual:

$git checkout -b sign-up

7.1.1 Debug and Rails Environments

The profiles in this section will be the first truly dynamic pages in our application. Although the view will exist as a single page of code, each profile will be customized using information retrieved from the application’s database. As preparation for adding dynamic pages to our sample application, now is a good time to add some debug information to our site layout (Listing 7.1). This displays some useful information about each page using the built-indebugmethod andparamsvariable (which we’ll learn more about in Section 7.1.2).

图7.2

图7.2:A mockup of our best guess at the final profile page.

Listing 7.1:Adding some debug information to the site layout.

app/views/layouts/application.html.erb

<html> . . . <body><%=render'layouts/header'%><divclass="container"><%=yield%><%=render'layouts/footer'%><%=debug(params)ifRails.env.development?%>div> body> html>

Since we don’t want to display debug information to users of a deployed application, Listing 7.1 uses

ifRails.env.development?

to restrict the debug information to thedevelopment environment, which is one of three environments defined by default in Rails (Box 7.1).3In particular,Rails.env.development?istrueonly in a development environment, so the embedded Ruby

<%=debug(params)ifRails.env.development?%>

won’t be inserted into production applications or tests. (Inserting the debug information into tests probably wouldn’t do any harm, but it probably wouldn’t do any good, either, so it’s best to restrict the debug display to development only.)

To make the debug output look nicer, we’ll add some rules to the custom stylesheet created in Chapter 5, as shown in Listing 7.2.4

Listing 7.2:Adding code for a prettier debug box.

app/assets/stylesheets/custom.scss

@import"bootstrap-sprockets";@import"bootstrap";.../*miscellaneous*/.debug_dump{clear:both;float:left;width:100%;margin-top:45px;}

The result is shown inFigure 7.3.

Figure 7.3

Figure 7.3:The sample application Home page with debug information.

The debug output inFigure 7.3gives potentially useful information about the page being rendered:

#"static_pages", "action"=>"home"} permitted: false>

This is a literal representation ofparams, which is basically a hash, and in this case identifies the controller and action for the page. We’ll see another example in Section 7.1.2.

The specific representation of the debug information is exactly the kind of thing that might depend on the exact version of Rails, and in fact prior to Rails 7debug(params)was displayed in the so-called YAML format.5Because Rails has generally been stable at the level of this tutorial for many years now, some of the screenshots still show this earlier representation (Figure 7.4). Being able to handle such minor discrepancies is a hallmark of technical sophistication (Box 1.2).

Figure 7.4

Figure 7.4:The debug information in an earlier version of Rails.

Exercises

  1. Visit /about in your browser and use the debug information to determine the controller and action of theparamshash.

  2. In the Rails console, pull the first user out of the database and assign it to the variableuser. What is the output ofputs user.attributes.to_yaml? Compare this to using theymethod viay user.attributes.

7.1.2 A Users Resource

In order to make a user profile page, we need to have a user in the database, which introduces a chicken-and-egg problem: How can the site have a user before there is a working signup page? Happily, this problem has already been solved—in Section 6.3.4, we created a User record by hand using the Rails console, so there should be one user in the database:

$ rails console>>User.count=> 1>>User.first=> #

(If you don’t currently have a user in your database, you should visit Section 6.3.4 now and complete it before proceeding.) We see from the console output above that the user has id1, and our goal now is to make a page to display this user’s information. We’ll follow the conventions of the REST architecture favored in Rails applications (Box 2.2), which means representing data asresourcesthat can be created, shown, updated, or destroyed—four actions corresponding to the four fundamental operationsPOST,GET,PATCH, andDELETEdefined by theHTTP standard(Box 3.2).

When following REST principles, resources are typically referenced using the resource name and a unique identifier. What this means in the context of users—which we’re now thinking of as a Usersresource—is that we should view the user with id1by issuing aGETrequest to the URL /users/1. Here theshowaction isimplicitin the type of request—when Rails’ REST features are activated,GETrequests are automatically handled by theshowaction.

We saw in Section 2.2.1 that the page for a user with id1has URL /users/1. Unfortunately, visiting that URL right now just gives an error (Figure 7.5).

Figure 7.5

Figure 7.5:The current state of /users/1.

We can get the routing for /users/1 to work by adding a single line to our routes file (config/routes.rb):

resources:users

The result appears in Listing 7.3.

Listing 7.3:Adding a Users resource to the routes file.

config/routes.rb

Rails.application.routes.drawdoroot"static_pages#home"get"/help",to:"static_pages#help"get"/about",to:"static_pages#about"get"/contact",to:"static_pages#contact"get"/signup",to:"users#new"resources:usersend

Although our immediate motivation is making a page to show users, the single lineresources :usersdoesn’t just add a working /users/1 URL; it endows our sample application withallthe actions needed for a RESTful Users resource,6along with a large number of named routes (Section 5.3.3) for generating user URLs. The resulting correspondence of URLs, actions, and named routes is shown in Table 7.1. (Compare to Table 2.2.) Over the course of the next three chapters, we’ll cover all of the other entries in Table 7.1 as we fill in all the actions necessary to make Users a fully RESTful resource.

Table 7.1:RESTful routes provided by the Users resource in Listing 7.3.

HTTP request method

URL

Action

Named route

Purpose

GET

/users

index

users_path

page to list all users

GET

/users/1

show

user_path(user)

page to show user

GET

/users/new

new

new_user_path

page to make a new user (signup)

POST

/users

create

users_path

create a new user

GET

/users/1/edit

edit

edit_user_path(user)

page to edit user with id1

PATCH

/users/1

update

user_path(user)

update user

DELETE

/users/1

destroy

user_path(user)

delete user

With the code in Listing 7.3, the routing works, but there’s still no page there (Figure 7.6). To fix this, we’ll begin with a minimalist version of the profile page, which we’ll flesh out in Section 7.1.4.

Figure 7.6

Figure 7.6:The URL /users/1 with routing but no page.

We’ll use the standard Rails location for showing a user, which isapp/views/users/show.html.erb. Unlike thenew.html.erbview, which we created with the generator in Listing 5.38, theshow.html.erbfile doesn’t currently exist, so you’ll have to create it by hand,7然后填充内容见清单7.4.

Listing 7.4:A stub view for showing user information.

app/views/users/show.html.erb

<%=@user.name%>,<%=@user.email%>

This view uses embedded Ruby to display the user’s name and email address, assuming the existence of an instance variable called@user. Of course, eventually the real user show page will look very different (and won’t display the email address publicly).

In order to get the user show view to work, we need to define an@uservariable in the correspondingshowaction in the Users controller. As you might expect, we use thefindmethod on the User model (Section 6.1.4) to retrieve the user from the database, as shown in Listing 7.5.

Listing 7.5:The Users controller with ashowaction.

app/controllers/users_controller.rb

classUsersController<ApplicationControllerdefshow@user=User.find(params[:id])enddefnewendend

Here we’ve usedparamsto retrieve the user id. When we make the appropriate request to the Users controller,params[:id]will be the user id1, so the effect is the same as thefindmethodUser.find(1)we saw in Section 6.1.4. (Technically,params[:id]is the string"1", butfindis smart enough to convert this to an integer.)

With the user view and action defined, the URL /users/1 works perfectly, as seen inFigure 7.7. (If you haven’t restarted the Rails server since adding bcrypt, you may have to do so at this time. This sort of thing is a good application of technical sophistication (Box 1.2).) Note that the debug information inFigure 7.7confirms the value ofparams[:id]:

Figure 7.7

Figure 7.7:The user show page after adding a Users resource.

{"controller"=>"users","action"=>"show","id"=>"1"}

This is why the code

User.find(params[:id])

in Listing 7.5 finds the user with id1.

Exercises

  1. Using embedded Ruby, add thecreated_atandupdated_at“magic column” attributes to the user show page from Listing 7.4.

  2. Using embedded Ruby, addTime.nowto the user show page. What happens when you refresh the browser?

7.1.3 Debugger

We saw in Section 7.1.2 how the information from thedebugmethod could help us understand what’s going on in our application, but there’s also a more direct way to get debugging information. To see how it works, we just need to add a line consisting ofdebuggerto our application, as shown in Listing 7.6.

Listing 7.6:The Users controller with a debugger.

app/controllers/users_controller.rb

classUsersController<ApplicationControllerdefshow@user=User.find(params[:id])debuggerenddefnewendend

Now, when we visit /users/1, the Rails server shows anrdbg(Ruby debugger) prompt (Figure 7.8):

Figure 7.8

Figure 7.8:The debugger prompt in the Rails server.

(rdbg)

We can treat the debugger like a Rails console, issuing commands to figure out the state of the application:

(rdbg)@user.name"Michael Hartl"(rdbg)@user.email"michael@example.com"(rdbg)params[:id]"1"

To release the prompt and continue execution of the application, press Ctrl-D, then remove thedebuggerline from theshowaction (Listing 7.7).

Listing 7.7:The Users controller with the debugger line removed.

app/controllers/users_controller.rb

classUsersController<ApplicationControllerdefshow@user=User.find(params[:id])enddefnewendend

Whenever you’re confused about something in a Rails application, it’s a good practice to putdebugger接近你认为可能导致t的代码rouble. Inspecting the state of the system usingbyebugis a powerful method for tracking down application errors and interactively debugging your application.

Exercises

  1. With thedebuggerin theshowaction as in Listing 7.6, hit /users/1. Useputsto display the value of the YAML form of theparamshash.Hint: Refer to the relevant exercise in Section 7.1.1. How does it compare to the debug information shown by thedebugmethod in the site template?

  2. Put thedebuggerin the Usernewaction and hit /users/new. What is the value of@user?

7.1.4 A Gravatar Image and a Sidebar

Having defined a basic user page in the previous section, we’ll now flesh it out a little with a profile image for each user and the first cut of the user sidebar. We’ll start by adding a “globally recognized avatar”, orGravatar, to the user profile.8Gravatar is a free service that allows users to upload images and associate them with email addresses they control. As a result, Gravatars are a convenient way to include user profile images without going through the trouble of managing image upload, cropping, and storage; all we need to do is construct the proper Gravatar image URL using the user’s email address and the corresponding Gravatar image will automatically appear. (We’ll learn how to handle custom image upload in Section 13.4.)

Our plan is to define agravatar_forhelper function to return a Gravatar image for a given user, as shown in Listing 7.8.

Listing 7.8:The user show view with name and Gravatar.

app/views/users/show.html.erb

<%provide(:title,@user.name)%><h1><%=gravatar_for@user%><%=@user.name%>h1>

By default, methods defined in any helper file are automatically available in any view, but for convenience we’ll put thegravatar_formethod in the file for helpers associated with the Users controller. As noted in theGravatar documentation, Gravatar URLs are based on anMD5 hashof the user’s email address. In Ruby, the MD5 hashing algorithm is implemented using thehexdigestmethod, which is part of theDigestlibrary:

>>email="MHARTL@example.COM">>Digest::MD5::hexdigest(email.downcase)=> "1fda4469bcbec3badf5418269ffc5968"

Since email addresses are case-insensitive (Section 6.2.4) but MD5 hashes are not, we’ve used thedowncasemethod to ensure that the argument tohexdigestis all lowercase. (Because of the email downcasing callback in Listing 6.32, this will never make a difference in this tutorial, but it’s a good practice in case thegravatar_formethod ever gets used on email addresses from other sources.) The resultinggravatar_forhelper appears in Listing 7.9.

Listing 7.9:Defining agravatar_forhelper method.

app/helpers/users_helper.rb

moduleUsersHelper# Returns the Gravatar for the given user.defgravatar_for(user) gravatar_id=Digest::MD5::hexdigest(user.email.downcase) gravatar_url="https://secure.gravatar.com/avatar/#{gravatar_id}"image_tag(gravatar_url,alt: user.name,class:"gravatar")endend

The code in Listing 7.9 returns an image tag for the Gravatar with agravatarCSS class and alt text equal to the user’s name (which is especially convenient for visually impaired users using a screen reader).

The resulting profile page should appear as inFigure 7.9. The displayed Gravatar image is a generic default becausemichael@example.comisn’t a real email address and hence can’t be associated with a custom Gravatar. (In fact, as you can see by visiting it, theexample.comdomain is reserved for examples just like this one.) By the way, if you completed the exercises in Section 5.1.2, be sure to remove the CSS from Listing 5.11 so that the gravatar image displays correctly.

Figure 7.9

Figure 7.9:The user profile page with the default Gravatar.

让我们的应用程序display a custom Gravatar, we’ll use theupdatemethod (Section 6.1.5) to change the user’s email to something I control:9

$ rails console>>user=User.first>>user.update(name:"Example User",?>email:"example@railstutorial.org",?>password:"foobar",?>password_confirmation:"foobar")=> true

Here we’ve assigned the user the email addressexample@railstutorial.org, which I’ve associated with the Rails Tutorial logo, as seen in图7.10.

图7.10

图7.10:The user show page with a custom Gravatar.

The last element needed to complete the mockup from图7.1is the initial version of the user sidebar. We’ll implement it using theasidetag, which is used for content (such as sidebars) that complements the rest of the page but can also stand alone. We includerowandcol-md-4classes, which are both part of Bootstrap. The code for the modified user show page appears in Listing 7.10.

Listing 7.10:Adding a sidebar to the usershowview.

app/views/users/show.html.erb

<%provide(:title,@user.name)%><divclass="row"> <asideclass="col-md-4"> <sectionclass="user_info"> <h1><%=gravatar_for@user%><%=@user.name%>h1> section> aside> div>

With the HTML elements and CSS classes in place, we can style the profile page (including the sidebar and the Gravatar) with the SCSS shown in Listing 7.11.10(Note the nesting of the table CSS rules, which works only because of the Sass engine used by the asset pipeline.) The resulting page is shown in图7.11.

图7.11

图7.11:The user show page with a sidebar and CSS.

Listing 7.11:SCSS for styling the user show page, including the sidebar.

app/assets/stylesheets/custom.scss

.../*sidebar*/aside{section.user_info{margin-top:20px;}section{padding:10px 0;margin-top:20px;&:first-child{border:0;padding-top:0;}span{display:block;margin-bottom:3px;line-height:1;}h1{font-size:1.4em;text-align:left;letter-spacing:-1px;margin-bottom:3px;margin-top:0px;} } }.gravatar{float:left;margin-right:10px;}.gravatar_edit{margin-top:15px;}

Exercises

  1. Associate a Gravatar with your primary email address if you haven’t already. What is the MD5 hash associated with the image?

  2. Verify that the code in Listing 7.12 allows thegravatar_forhelper defined in Section 7.1.4 to take an optionalsizeparameter, allowing code likegravatar_foruser, size: 50in the view. (We’ll put this improved helper to use in Section 10.3.1.)

  3. The options hash used in the previous exercise is still commonly used, but as of Ruby 2.0 we can usekeyword argumentsinstead. Confirm that the code in Listing 7.13 can be used in place of Listing 7.12. What are the diffs between the two?

Listing 7.12:Adding an options hash in thegravatar_forhelper.

app/helpers/users_helper.rb

moduleUsersHelper# Returns the Gravatar for the given user.defgravatar_for(user, options={size:80})size=options[:size]gravatar_id=Digest::MD5::hexdigest(user.email.downcase)gravatar_url="https://secure.gravatar.com/avatar/#{gravatar_id}?s=#{size}"image_tag(gravatar_url,alt: user.name,class:"gravatar")endend

Listing 7.13:Using keyword arguments in thegravatar_forhelper.

app/helpers/users_helper.rb

moduleUsersHelper# Returns the Gravatar for the given user.defgravatar_for(user,size:80)gravatar_id=Digest::MD5::hexdigest(user.email.downcase) gravatar_url="https://secure.gravatar.com/avatar/#{gravatar_id}?s=#{size}"image_tag(gravatar_url,alt: user.name,class:"gravatar")endend

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

通过我们的在线订单和购买放置store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simplyemailinformation@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through ourContact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on theAccount page. If a user no longer desires our service and desires to delete his or her account, please contact us atcustomer-service@informit.comand we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive:www.e-skidka.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information toNevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read ourSupplemental privacy statement for California residentsin conjunction with this Privacy Notice. TheSupplemental privacy statement for California residents培生的承诺遵守加州解释道ornia law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Pleasecontact usabout this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020