Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Preview
Start a free Courses trial
to watch this video
The controller is responsible for handling the browser request. It CONTROLS the model and the view to generate a response.
When you access the list of all "Post" objects, the request gets sent to the "index" method of the "PostsController" class.
- Rails creates the source code for controller classes in the "app/controllers/" subdirectory.
- The "PostsController" class will be in "posts_controller.rb".
- The request is handled by the "index" method or action (controller methods that respond to requests are sometimes called "actions").
This section of the log shows where
Rails proceed to get requests for
0:00
the posts path.
0:04
The request gets sent to the index
method of the PostsController class.
0:05
The controller is responsible for
handling the browser requests.
0:10
It controls the model and
the view to generate a response.
0:13
The controller receives the request,
0:16
loads the requested data via
the model usually from a database.
0:18
And then inserts that data into the view,
which is usually an HTML page.
0:22
The result of rendering the HTML is then
returned to the browser as a response.
0:27
Most of the code for
your app including controllers, models and
0:32
views will reside within
the app sub directory.
0:35
Rails create source files for controller
classes in the app controllers directory.
0:38
Here's the PostController class,
in posts_controller.rb.
0:43
And here's the index method or action.
0:48
Controller methods that respond to
requests are sometimes called actions.
0:51
Doesn't look like much, but
0:55
that's because it's mostly using the
default operations to handle the request.
0:56
First, it loads some data
via the Post model class.
1:01
It calls the Post.all method
to load all post objects and
1:04
stores them in an instance variable.
1:08
Then the controller uses the data in
that instance variable to render a view.
1:10
By default it renders a template
with the same name as the action
1:15
within the same page layout
the rest of the application uses.
1:18
We could add an explicit call to
the render method and get the same result.
1:21
We could render the posts/index
template using a layout of application.
1:25
If we save this and then reload the page
in our browser, we'll get the same result.
1:33
So the controller loads model
data by calling Post.all and
1:38
then it renders the index view.
1:42
Next, we'll look at that model and
view in more detail.
1:44
You need to sign up for Treehouse in order to download course files.
Sign up