How to Set the Homepage Route in Rails
In this lesson, we are going to set the homepage of the application. This includes drawing the route and walking through how the route corresponds to the controller action and view template.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

In this lesson, we are going to set the homepage of the application. This includes drawing the route and walking through how the route corresponds to the controller action and view template.

If you go to the browser and type the homepage, which is localhost:3000, it goes to the default Ruby on Rails launch page.

large

And this is not what we want for our application. To set the right homepage, go to config directory and open a file called routes.rb.

In this file, add this line:

root to: "posts#index"

In this code, the part before the #, which in this case is posts is a call to the controller file. If you have a different controller file called, for example invoices, then you would have invoices instead of posts before the #. The next part, that is, index is a method call, also called the controller action.

Now, go to app/controllers and open the file called posts_controller.rb. In this file, you'll see that the scaffold built a lot of code for us. This is what the file looks like.

large

If you see, there's a method called index here that will get called in our routes.rb file.

To test, start your server with the command:

rails s

Next, go to the browser and refresh it. The new homepage should be:

medium

If you click on the New Post link, it'll take you to a form where you can fill the title, image and description fields. When you click on the button called Create Post, your record will be created.

medium

Once you create the post, this page will take you back to the home page where you can view, edit or delete this record.

So, that's how you set the homepage for your rails app.