Ruby On Rails Lesson
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.6. 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).
1. The browser issues a request for the /users URI.
2. Rails routes /users to the index action in the Users controller
Figure 2.11 A detailed diagram of MVC in Rails.
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.3
We start with a request issued from the browser—that is, the result of typing a URI 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 to the proper controller action based on the URI (and, as we’ll see in Box 3.2, the type of request). The code to create the mapping of user URIs to controller actions for the Users resource appears in Listing 2.2; this code effectively sets up the table of URI/action pairs seen in Table 2.1. (The strange notation :users is a symbol, which we’ll learn about in Section 4.3.3.)
The pagesfrom thetourin 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.3. Note the notation class UsersController < ApplicationController; this 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.)