Home > Articles

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

2.2 The Users Resource

In this section, we’ll implement the users data model in Section 2.1.1, along with a web interface to that model. The combination will constitute a Users resource, which will allow us to think of users as objects that can be created, read, updated, and deleted through the web via the HTTP protocol. As promised in the introduction, our Users resource will be created by a scaffold generator program, which comes standard with each Rails project. I urge you not to look too closely at the generated code; at this stage, it will only serve to confuse you.

Rails scaffolding is generated by passing the scaffold command to the rails generate script. The argument of the scaffold command is the singular version of the resource name (in this case, User), together with optional parameters for the data model’s attributes:3

$ rails generate scaffold User name:string email:string

      invoke  active_record
      create    db/migrate/<timestamp>_create_users.rb
      create    app/models/user.rb
      invoke    test_unit
      create      test/models/user_test.rb
      create      test/fixtures/users.yml
      invoke  resource_route
       route    resources :users
      invoke  scaffold_controller
      create    app/controllers/users_controller.rb
      invoke    erb
      create      app/views/users
      create      app/views/users/index.html.erb
      create      app/views/users/edit.html.erb
      create      app/views/users/show.html.erb
      create      app/views/users/new.html.erb
      create      app/views/users/_form.html.erb
      invoke    test_unit
      create      test/controllers/users_controller_test.rb
      create      test/system/users_test.rb
      invoke    helper
      create      app/helpers/users_helper.rb
      invoke      test_unit
      invoke    jbuilder
      create      app/views/users/index.json.jbuilder
      create      app/views/users/show.json.jbuilder
      create      app/views/users/_user.json.jbuilder
      invoke  assets
      invoke    scss
      create      app/assets/stylesheets/users.scss
      invoke  scss
      create    app/assets/stylesheets/scaffolds.scss

By including name:string and email:string, we have arranged for the User model to have the form shown in Figure 2.2. (Note that there is no need to include a parameter for id; Rails creates it automatically for use as the primary key in the database.)

To proceed with the toy application, we first need to migrate the database using rails db:migrate, as shown in Listing 2.4.

Listing 2.4: Migrating the database.

$ rails db:migrate
== CreateUsers: migrating ======================================
-- create_table(:users)
   -> 0.0027s
== CreateUsers: migrated (0.0036s) =============================

The effect of Listing 2.4 is to update the database with our new users data model. (We’ll learn more about database migrations starting in Section 6.1.1.)

Having run the migration in Listing 2.4, we can run the local webserver in a separate tab (Figure 1.15). Users of the cloud IDE should first add the same configuration as in Section 1.2.2 to allow the toy app to be served (Listing 2.5).

Listing 2.5: Allowing connections to the local web server.

config/environments/development.rb
Rails.application.configure do
  .
  .
  .
  # Allow Cloud9 connections.
  config.hosts.clear
end

Then run the Rails server as in Section 1.2.2:

$ rails server

Now the toy application should be available on the local server as described in Section 1.2.2. In particular, if we visit the root URL at / (read “slash”, as noted in Section 1.2.4), we get the same “hello, world!” page shown in Figure 1.20.

2.2.1 A User Tour

In generating the Users resource scaffolding in Section 2.2, Rails created a large number of pages for manipulating users. For example, the page for listing all users is at /users, and the page for making a new user is at /users/new. The rest of this section is dedicated to taking a whirlwind tour through these user pages. As we proceed, it may help to refer to Table 2.1, which shows the correspondence between pages and URLs.

We start with the page that shows all the users in our application, called index and located at /users. As you might expect, initially there are no users at all (Figure 2.4).

FIGURE 2.4

Figure 2.4: The initial index page for the Users resource (/users).

Table 2.1: The correspondence between pages and URLs for the Users resource.

URL

Action

Purpose

/users

index

page to list all users

/users/1

show

page to show user with id 1

/users/new

new

page to make a new user

/users/1/edit

edit

page to edit user with id 1

To make a new user, we can click on the New User link in Figure 2.4 to visit the new page at /users/new, as shown in Figure 2.5. In Chapter 7, this will become the user signup page.

FIGURE 2.5

Figure 2.5: The new user page (/users/new).

We can create a user by entering name and email values in the text fields and then clicking the Create User button. The result is the user show page at /users/1, as seen in Figure 2.6. (The green welcome message is accomplished using the flash, which we’ll learn about in Section 7.4.2.) Note that the URL is /users/1; as you might suspect, the number 1 is simply the user’s id attribute from Figure 2.2. In Section 7.1, this page will become the user’s profile page.

FIGURE 2.6

Figure 2.6: The page to show a user (/users/1).

To change a user’s information, we click the Edit link to visit the edit page at /users/1/edit (Figure 2.7). By modifying the user information and clicking the Update User button, we arrange to change the information for the user in the toy application (Figure 2.8). (As we’ll see in detail starting in Chapter 6, this user data is stored in a database back end.) We’ll add user edit/update functionality to the sample application in Section 10.1.

FIGURE 2.7

Figure 2.7: The user edit page (/users/1/edit).

FIGURE 2.8

Figure 2.8: A user with updated information.

Now we’ll create a second user by revisiting the new page at /users/new and submitting a second set of user information. The resulting user index is shown in Figure 2.9. In Section 7.1, we will develop the user index into a more polished page for showing all users.

FIGURE 2.9

Figure 2.9: The user index page (/users) with a second user.

Having shown how to create, show, and edit users, we come finally to destroying them (Figure 2.10). You should verify that clicking on the link in Figure 2.10 destroys the second user, yielding an index page with only one user. (If it doesn’t work, be sure that JavaScript is enabled in your browser; Rails uses JavaScript to issue the request needed to destroy a user.) Section 10.4 adds user deletion to the sample app, taking care to restrict its use to a special class of administrative users.

FIGURE 2.10

Figure 2.10: Destroying a user.

Exercises

Solutions to the exercises are available to all Rails Tutorial purchasers at https://www.railstutorial.org/aw-solutions.

To see other people’s answers and to record your own, subscribe to the Rails Tutorial course or to the Learn Enough All Access Bundle.

  1. (For readers who know CSS) Create a new user, then use your browser’s HTML inspector to determine the CSS id for the text “User was successfully created.” What happens when you refresh your browser?

  2. What happens if you try to create a user with a name but no email address?

  3. What happens if you try create a user with an invalid email address, like “@example.com”?

  4. Destroy each of the users created in the previous exercises. Does Rails display a message by default when a user is destroyed?

2.2.2 MVC in Action

Now that we’ve completed a quick overview of the Users resource, let’s examine one particular part of it in the context of the model-view-controller (MVC) pattern introduced in Section 1.2.3. Our strategy will be to describe the results of a typical browser hit—a visit to the user index page at /users—in terms of MVC (Figure 2.11).

FIGURE 2.11

Figure 2.11: A detailed diagram of MVC in Rails.

Here is a summary of the steps shown in Figure 2.11:

  1. The browser issues a request for the /users URL.

  2. Rails routes /users to the index action in the Users controller.

  3. The index action asks the User model to retrieve all users (User.all).

  4. The User model pulls all the users from the database.

  5. The User model returns the list of users to the controller.

  6. The controller captures the users in the @users variable, which is passed to the index view.

  7. The view uses embedded Ruby to render the page as HTML.

  8. The controller passes the HTML back to the browser.4

Now let’s take a look at the these steps in more detail. We start with a request issued from the browser—that is, the result of typing a URL in the address bar or clicking on a link (Step 1 in Figure 2.11). This request hits the Rails router (Step 2), which dispatches the request to the proper controller action based on the URL (and, as we’ll see in Box 3.2, the type of request). The code to create the mapping of user URLs to controller actions for the Users resource appears in Listing 2.6. This code effectively sets up the table of URL/action pairs seen in Table 2.1. (The strange notation :users is a symbol, which we’ll learn about in Section 4.3.3.)

Listing 2.6: The Rails routes, with a rule for the Users resource.

config/routes.rb
Rails.application.routes.draw do
  resources :users
  root 'application#hello'
end

While we’re looking at the routes file, let’s take a moment to associate the root route with the users index, so that “slash” goes to /users. Recall from Listing 2.3 that we added the root route

root 'application#hello'

so that the root route went to the hello action in the Application controller. In the present case, we want to use the index action in the Users controller, which we can arrange using the code shown in Listing 2.7.

Listing 2.7: Adding a root route for users.

config/routes.rb
Rails.application.routes.draw do
  resources :users
  root 'users#index'
end

A controller contains a collection of related actions, and the pages from the tour in Section 2.2.1 correspond to actions in the Users controller. The controller generated by the scaffolding is shown schematically in Listing 2.8. Note the code class UsersController < ApplicationController, which is an example of a Ruby class with inheritance. (We’ll discuss inheritance briefly in Section 2.3.4 and cover both subjects in more detail in Section 4.4.)

Listing 2.8: The Users controller in schematic form.

app/controllers/users_controller.rb
class UsersController < ApplicationController
  .
  .
  .
  def index
    .
    .
    .
  end
  def show
    .
    .
    .
  end

  def new
    .
    .
    .
  end

  def edit
    .
    .
    .
  end

  def create
    .
    .
    .
  end

  def update
    .
    .
    .
  end

  def destroy
    .
    .
    .
  end
end

You might notice that there are more actions than there are pages. The index, show, new, and edit actions all correspond to pages from Section 2.2.1, but there are additional create, update, and destroy actions as well. These actions don’t typically render pages (although they can); instead, their main purpose is to modify information about users in the database.

This full suite of controller actions, summarized in Table 2.2, represents the implementation of the REST architecture in Rails (Box 2.2), which is based on the idea of representational state transfer, a concept identified and named by computer scientist Roy Fielding.5 Note from Table 2.2 that there is some overlap in the URLs; for example, both the user show action and the update action correspond to the URL /users/1. The difference between them is the HTTP request method they respond to. We’ll learn more about HTTP request methods starting in Section 3.3.

Table 2.2: RESTful routes provided by the Users resource in Listing 2.6.

HTTP request

URL

Action

Purpose

GET

/users

index

page to list all users

GET

/users/1

show

page to show user with id 1

GET

/users/new

new

page to make a new user

POST

/users

create

create a new user

GET

/users/1/edit

edit

page to edit user with id 1

PATCH

/users/1

update

update user with id 1

DELETE

/users/1

destroy

delete user with id 1

To examine the relationship between the Users controller and the User model, let’s focus on the index action, shown in Listing 2.9. (Learning how to read code even when you don’t fully understand it is an important aspect of technical sophistication (Box 1.2).)

Listing 2.9: The simplified user index action for the toy application.

app/controllers/users_controller.rb
class UsersController < ApplicationController
  .
  .
  .
  def index
    @users = User.all
  end
  .
  .
  .
end

This index action includes the line @users = User.all (Step 3 in Figure 2.11), which asks the User model to retrieve a list of all the users from the database (Step 4), and then places them in the variable @users (pronounced “at-users”) (Step 5).

The User model itself appears in Listing 2.10. Although it is rather plain, it comes equipped with a large amount of functionality because of inheritance (Section 2.3.4 and Section 4.4). In particular, by using the Rails library called Active Record, the code in Listing 2.10 arranges for User.all to return all the users in the database.

Listing 2.10: The User model for the toy application.

app/models/user.rb
class User < ApplicationRecord
end

Once the @users variable is defined, the controller calls the view (Step 6), shown in Listing 2.11. Variables that start with the @ sign, called instance variables, are automatically available in the views; in this case, the index.html.erb view in Listing 2.11 iterates through the @users list and outputs a line of HTML for each one. (Remember, you aren’t supposed to understand this code right now. It is shown only for purposes of illustration.)

Listing 2.11: The view for the users index.

app/views/users/index.html.erb
<p id="notice"><%= notice %></p>

<h1>Users</h1>

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Email</th>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody>
    <% @users.each do |user| %>
      <tr>
        <td><%= user.name %></td>
        <td><%= user.email %></td>
        <td><%= link_to 'Show', user %></td>
        <td><%= link_to 'Edit', edit_user_path(user) %></td>
        <td><%= link_to 'Destroy', user, method: :delete,
                         data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>
  </tbody>
</table>

<br>

<%= link_to 'New User', new_user_path %>

The view converts its contents to HTML (Step 7), which is then returned by the controller to the browser for display (Step 8).

Exercises

Solutions to the exercises are available to all Rails Tutorial purchasers at https://www.railstutorial.org/aw-solutions.

To see other people’s answers and to record your own, subscribe to the Rails Tutorial course or to the Learn Enough All Access Bundle.

  1. By referring to Figure 2.11, write out the analogous steps for visiting the URL /users/1/edit.

  2. Find the line in the scaffolding code that retrieves the user from the database in the previous exercise. Hint: It’s in a special location called set_user.

  3. What is the name of the view file for the user edit page?

2.2.3 Weaknesses of this Users Resource

Though good for getting a general overview of Rails, the scaffold Users resource suffers from a number of severe weaknesses.

  • No data validations. Our User model accepts data such as blank names and invalid email addresses without complaint.

  • No authentication. We have no notion of logging in or out, and no way to prevent any user from performing any operation.

  • No tests. This isn’t technically true—the scaffolding includes rudimentary tests— but the generated tests don’t test for data validation, authentication, or any other custom requirements.

  • No style or layout. There is no consistent site styling or navigation.

  • No real understanding. If you understand the scaffold code, you probably shouldn’t be reading this book.

  • + Share This
  • 🔖 Save To Your Account

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

For orders and purchases placed through our online 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, simply email information@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 our Contact 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 the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and 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.informit.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 to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California 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


Please contact us about 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