Home > Articles > Programming > Ruby

  • Print
  • + Share This
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. This 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, doing so will simply 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/20140821011110_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
      invoke    helper
      create      app/helpers/users_helper.rb
      invoke      test_unit
      create        test/helpers/users_helper_test.rb
      invoke    jbuilder
      create      app/views/users/index.json.jbuilder
      create      app/views/users/show.json.jbuilder
      invoke  assets
      invoke    coffee
      create      app/assets/javascripts/users.js.coffee
      invoke    scss
      create      app/assets/stylesheets/users.css.scss
      invoke  scss
      create    app/assets/stylesheets/scaffolds.css.scss

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

To proceed with the toy application, we first migrate the database using Rake (Box 2.1):


$ bundle exec rake db:migrate
==  CreateUsers: migrating ==================================================
-- create_table(:users)
   -> 0.0017s
==  CreateUsers: migrated (0.0018s) =========================================

This simply updates the database with our new users data model. (We’ll learn more about database migrations starting in Section 6.1.1.) To ensure that the command uses the version of Rake corresponding to our Gemfile, we need to run rake using bundle exec. On many systems, including the cloud IDE, you can omit bundle exec, but it is necessary on some systems, so we’ll include it here for completeness.

With that, we can run the local web server in a separate tab (Figure 1.7) as follows:4

$ rails server -b $IP -p $PORT    # Use only `rails server` if running locally

Now the toy application should be available on the local server as described in Section 1.3.2. (If you’re using the cloud IDE, be sure to open the resulting development server in a new browser tab, not inside the IDE itself.)

2.2.1 A User Tour

If we visit the root URL at / (read “slash,” as noted in Section 1.3.4), we get the same default Rails page shown in Figure 1.9. In generating the Users resource scaffolding, however, we have also 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.

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

We start with the page to show all the users in our application, called index; as you might expect, initially there are no users (Figure 2.4).

Figure 2.4

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

To make a new user, we visit the new page, as shown in Figure 2.5. (Since the http://0.0.0.0:3000 or cloud IDE part of the address is implicit whenever we are developing locally, we’ll omit it from now on.) In Chapter 7, this will become the user sign-up 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, 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.

Figure 2.6

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

To change a user’s information, we visit the edit page (Figure 2.11 on page 67). By modifying the user information and clicking the Update User button, we 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 9.1.

Figure 2.8

Figure 2.8 A user with updated information.

Figure 2.11

Figure 2.11 The user edit page (/users/1/edit).

Now we’ll create a second user by revisiting the new page and submitting a second set of user information; the resulting user index is shown in Figure 2.9. Section 7.1 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.

Now that we know how to create, show, and edit users, we come finally to the process of 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, make sure that JavaScript is enabled in your browser; Rails uses JavaScript to issue the request needed to destroy a user.) Section 9.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.

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.3.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 the MVC pattern (Figure 2.7).

Figure 2.7

Figure 2.7 A detailed diagram of MVC in Rails.

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

  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.5

Now let’s take a look at these 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.7). This request is sent to the Rails router (Step 2), which it dispatches 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.2; 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.2 The Rails routes, with a rule for the Users resource.


config/routes.rb
____________________________________________________________________________
Rails.application.routes.draw do
  resources :users
  .
  .
  .
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 1.10 that we changed

# root 'welcome#index'

to read

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.3. (At this point, I also recommend removing the hello action from the Application controller if you added it at the beginning of this section.)

Listing 2.3 Adding a root route for users.


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

The pages from the tour in Section 2.2.1 correspond to actions in the Users controller, which is a collection of related actions. The controller generated by the scaffolding is shown schematically in Listing 2.4. In this listing, the notation class UsersController < ApplicationController, 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.4 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 may notice that there are more actions than there are pages; in this listing, 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 identified and named by computer scientist Roy Fielding.6 As seen in Table 2.2, 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 to which they respond. 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.2.

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 a simplified version of the index action, shown in Listing 2.5. (The scaffold code is ugly and confusing, so it’s suppressed here.)

Listing 2.5 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.7), which asks the User model to retrieve a list of all 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.6; 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.6 arranges for User.all to return all the users in the database.

Listing 2.6 The User model for the toy application.

app/models/user.rb
____________________________________________________________________________
class User < ActiveRecord::Base
end
____________________________________________________________________________

Once the @users variable is defined, the controller calls the view (Step 6), shown in Listing 2.7. 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.7 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.7 The view for the user index.

app/views/users/index.html.erb
____________________________________________________________________________
<h1>Listing users</h1>

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

<% @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 %>
</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).

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