Routes Controller and View

Collapse Content

See Creating a Full Rails Site for our guide through this topic.

Rails Server

Enter the following command in your terminal to start your app's server:

rails server 

On cloud9:

rails server -b $IP -p $PORT 


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

Here's a standard route that maps /about to the store controller's about action:

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

Root route:

root to: 'store#home'

Multiple standard routes can be created in one line:

resources :products

git and Heroku

Add files to git

  • git add . - Adds everything to git.
  • git commit -m "message about feature" - Commits your changes to git.


  • git push heroku master - pushed your updated code to Heroku.
  • heroku run rake db:migrate - runs database migrations on your Heroku site.
  • heroku run console - run the Rails console on your Heroku app.


A controller controls access to an application and makes data available to the view.

rails g controller Store home - generates a Store controller with a home action and associated files.

class StoreController < ApplicationController
  def home
    @title = "Automated Store"

@title is now available for the view file to use (home.html.erb).

Usually, the controller makes data from the model available to the view. For example:

 def index
    @products = Product.all 


The view folders consist of html.erb page templates that are processed and sent to the user. Each template can contain Ruby code to display data from the controller.

Ruby code can be included in two ways:

  • <% %> - Execute code without returning anything
  • <%= %> - Execute code and display its output

Example: This loops through products and displays the name of each product.

<h1> All Products </h1> 
<% @products.each do |product| %> 
<%= %> <br> 
<% end %>


General Format

link_to "Text To Display", "URLofLink"

Ruby HTML Looks Like
link_to "Google", "" <a href="">Google</a> Google
link_to "About", about_path <a href="/about">About</a> About
<%= link_to, @product %> <a href="/products/3">Cow</a> 1 Cow

1. For a product named Cow with an ID of 3.

/rails/info/routes - view all your app's routes.

Database commands

  • rake db:seed - Run seeds.rb file to create sample data.
  • rake db:reset - Reset the database and run the seeds file.


Partials files are marked with an underscore, e.g: layouts/_header.html.erb.

They are rendered without the _: <%= render 'layouts/header' %>

Partials are often used to display a single item:


<li><%= link_to, product %></b></li>

You can display a list of products by passing a product variable to _product:

    <% @products.each do |prod| %>
        <%= render 'products/product', product: prod %>
    <% end %>

This can be shortened to:

<% @products.each do |product| %>
  <%= render product %>
<% end %>

And here's the magically short version:

  <%= render @products %>
Contact Us
Sign in or email us at [email protected]