Let's start hooking up the backend with the routes. To give you a refresher, the routes.rb file is where you can set up links to your various pages. In this lesson, we're going to set up some routes so that we can start displaying things on the web page.
The first thing we need to do is to set the root path. The root path is exactly what it sounds like, the default path that the user is directed to when the user goes to the home page.
In our web app, we want to set the root path to be pointed to the index page of Post. We can do this by adding the following to your routes.rb file.
root 'posts#index'
Now, if we go into our terminal and run rake routes, we should see that our root page is pointed to posts#index.
If you haven't already, start up your rails server and go to http://localhost:3000/, you should get an error saying that no template was found.
Missing Template Error
In Rails, when you get the Missing Template Error, it means that you are missing a view file for the application to render. If you recall from the Ideator post, Rails will try to find a view file with the same name as the controller action being called.
By default, when a method is triggered in the controller (in this case, the
indexmethod is triggered), then Rails will try to find anhtmlfile that has the same name as the method (in this caseindex) to display to the user in theviewsdirectory under the controller name's folder (Rails will also try to look into the inherited controller's folder, but let's not get into this right now).When Rails can't find a file with the same name as the controller action being called, it will give you the "Missing Template" error. In this case you have mainly two options:
- Create the file
For example, if the
indexaction inposts_controller.rbis called, then create a file calledindex.html.erbinside theapps/views/postsdirectory.
- Redirect the user in the controller method
This is used a lot in
create,update, ordestroyactions.For example, this code will give you a "Missing Template" error:
def create @post = Post.find(params[:id]) @post.create(post_params) endBut if you redirect the user like this, the error will disappear:
def create @post = Post.find(params[:id]) @post.create(post_params) redirect_to root_path end
In this case, instead of redirecting the user, let's go ahead and create index.html.erb in our apps/views/posts folder, and add a Hello World to test it out.
<h1>Hello World</h1>
Now let's navigate ourselves back to the browser and refresh the page. We should now see "Hello World" displayed on the page!