Now that we understand how each individual component works in MVC, let's look at how everything works together.
The following diagram describes what happens behind the scenes in a Rails application:
Let's go through each step.
A user makes an HTTP request
The request passes through the Rails Router
/ideas/1
through a GET
request, the Rails Router will choose to use the IdeasController
's show
method, since it is defined as such in the routes.rb
file: Prefix Verb URI Pattern Controller#Action
root GET / ideas#index
ideas GET /ideas(.:format) ideas#index
POST /ideas(.:format) ideas#create
new_idea GET /ideas/new(.:format) ideas#new
edit_idea GET /ideas/:id/edit(.:format) ideas#edit
idea GET /ideas/:id(.:format) ideas#show
PATCH /ideas/:id(.:format) ideas#update
PUT /ideas/:id(.:format) ideas#update
DELETE /ideas/:id(.:format) ideas#destroy
Notice how the GET
request for the URI pattern /ideas/:id
is mapped to ideas#show
(the show
action in the ideas
controller).
The controller receives the request
params
.params[:id]
to access the id
parameterIf the controller has some code that makes a call to the model, the model receives the request to do the job
@idea = Idea.find(params[:id])
in the show
method in the controller will request the model to fetch an Idea
with the id
of params[:id]
The database is accessed if the model makes a request. The data is then sent back to the model.
Idea.find(params[:id])
code would go into the database and do the work of finding the Idea
with the id
of params[:id]
The changes in the model will be sent to the controller so that it has the latest information
The view then displays the information
Instance variables defined in a controller method can be used in the corresponding view file
@ideas
defined in the index
method of ideas_controller.rb
can be used in the view file, index.html.erb
The controller then returns the response body (HTML, XML, etc.) and metadata (caching headers, redirects) to the server. The server combines the raw data into a proper HTTP response and sends it to the user.
While you build your apps, always have this flow in mind. Once you become familiar with how the application works together, you'll have an easier time debugging and writing code.