Routes and Views


Collapse Content

You created two pages, so now it's time to fix their URLs and content.

Adjusting the Routes

The URLs don’t look so nice, so let’s change them. Open up routes.rb and look at What Rails created:

config/routes.rb

get 'store/home'
get 'store/about'

The first line above maps visits from the URL '/store/home' to StoreController's home action, which returns the home web page.

Let's change the about route to the following:

get 'about', to: 'store#about'

This will map the shorter URL '/about' to StoreController's about action. It follows this general format of a route:

get 'URL', to: 'controller#action'

A route first states what URL it matches with, and then what controller and action it maps to. Later, we'll learn about other ways to specify routes.

Now let's set up a home page for our site to replace the default one. Instead of putting in a a URL, we'll just use the word root to mark the root URL itself:

root to: 'store#home'

Now routes.rb should look like this:

Rails.application.routes.draw do

  get 'about', to: 'store#about'
  root to: 'store#home'

  # lots of comments...
end

We can now navigate to the home page / of our site:

http://localhost:3000/

The default Rails page has been replaced by our own! The page doesn't say much, but that's something we can now change.

Adjusting the Page

In Rails, the view templates for StoreController are placed in the folder app/views/store:

Each action in the controller has a corresponding template for it. Since we created 2 actions about and home, we'll find 2 templates with those names.

Open up the file in store called home.html.erb and you should see this HTML:

<h1>Store#home</h1>
<p>Find me in app/views/store/home.html.erb</p>

Let's replace the HTML with something more relevant:

<h1>Automated Store</h1>
<p>You will be able to buy great things on this store.</p>

(See the HTML tutorial if you need to review your HTML basics.)

Now reload your home page and view your very own site:

More Pages

Editing your About Page

Edit the content of your about page, just like you did for your home page. It should have a <h1> heading that says "About the Store", and it should have a paragraph of content.

Creating a Contact Page

Create a new contact page for your site at /contact and give it a <h1> heading "Contact Us".

Guidelines

Need help with this page or the last? See this screencast.

Challenge

What action in StoreController does get 'store/about' map to?

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Challenge

Let's say you want to add a contact page to your site so people can contact you by visiting /contact. You add an action contact to StoreController. What route should you create for it in routes?

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Contact Us
Sign in or email us at [email protected]