Custom Routes for Pages in a Rails Application
Learn how to integrate static routes and pages in a Ruby on Rails application.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

If you see in the previous lesson, the controller added all the routes for us. Go to routes.rb, and you can see the routes for contact, about and home page.


Though this is great, I'd like to make some changes to it because I don't like to go to some website, and from there navigate to pages and then to contact, about or home. Instead I will create a custom route for each of these pages.

get "about" , to: "pages#about"

With this code, I can go to my localhost and type /about in the URL bar, and it will take me to the same page.

To check this on the browser, let's restart the rails server with the command rails s. Now, go to the browser and type the original URL which is localhost:3000/pages/about. This will give you an error message as this page is no longer a route.


If you closely at this error message, you can see the routes for each file. The second line has the route for the about page, which is now /about and not pages/about.

If you now remove pages and just type localhost:3000/about, it will take you to the about page.


Now, I'm going to make this change to all my routes in the routes.rb file. This is what the updated file looks like.


I haven't changed the home page because I want to do something different with it in subsequent lessons.

If you're wondering what this code means, it is essentially telling the framework to call the contact method in the pages controller when the browser sends a http get request for contact. To cross check, go to 'pages_controller.rb` and this is what you'll see:


A cool thing about these custom routes is you can pass values to these methods from your html file. For example, if I want to have a different title for my about page, I will go to the method and keep my title in a variable.

def about
  @title = "My cool page"


Next, I go to about.html.erb file, and access the title variable with embedded ruby.

<%= @title%>


I can check this change in the browser now.


That was easy, right?