Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
The Controller1:47 with Jay McGavren
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
the posts path.
The request gets sent to the index method of the PostsController class.
The controller is responsible for handling the browser requests.
It controls the model and the view to generate a response.
The controller receives the request,
loads the requested data via the model usually from a database.
And then inserts that data into the view, which is usually an HTML page.
The result of rendering the HTML is then returned to the browser as a response.
Most of the code for your app including controllers, models and
views will reside within the app sub directory.
Rails create source files for controller classes in the app controllers directory.
Here's the PostController class, in posts_controller.rb.
And here's the index method or action.
Controller methods that respond to requests are sometimes called actions.
Doesn't look like much, but
that's because it's mostly using the default operations to handle the request.
First, it loads some data via the Post model class.
It calls the Post.all method to load all post objects and
stores them in an instance variable.
Then the controller uses the data in that instance variable to render a view.
By default it renders a template with the same name as the action
within the same page layout the rest of the application uses.
We could add an explicit call to the render method and get the same result.
We could render the posts/index template using a layout of application.
If we save this and then reload the page in our browser, we'll get the same result.
So the controller loads model data by calling Post.all and
then it renders the index view.
Next, we'll look at that model and view in more detail.
You need to sign up for Treehouse in order to download course files.Sign up