- 2.1 Planning the Application
- 2.2 The Users Resource
- 2.3 The Microposts Resource
- 2.4 Conclusion
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: 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: 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: 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: The user edit page (/users/1/edit).
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: 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: 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.
(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?
What happens if you try to create a user with a name but no email address?
What happens if you try create a user with an invalid email address, like “@example.com”?
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: A detailed diagram of MVC in Rails.
Here is a summary of the steps shown in Figure 2.11:
The browser issues a request for the /users URL.
Rails routes /users to the index action in the Users controller.
The index action asks the User model to retrieve all users (User.all).
The User model pulls all the users from the database.
The User model returns the list of users to the controller.
The controller captures the users in the @users variable, which is passed to the index view.
The view uses embedded Ruby to render the page as HTML.
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.
By referring to Figure 2.11, write out the analogous steps for visiting the URL /users/1/edit.
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.
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.