Controllers to Views

Premium Content - Free Preview

We generated a controller before, so let's open it up and see what it does.

The Controller

Open up app/controllers/store_controller.rb:

class StoreController < ApplicationController
  def home

  def about

This code is really simple. The first line declares the name of the class and uses a < to show that it inherits from ApplicationController, which provides all the behind-the-scenes functionality of the controller.

The methods home and about don't actually have anything in them. However, Rails will automagically return the template in 'views/store' with the name of the controller action. That's why navigating to about and home returned those pages instead of nothing.

The Title

Open up the root of your site in your browser. Look at the title of the page in the tab on top. It should say the name you gave your application, such as TheAutomatedStore. This title is used on search results, Facebook and other sites that refer to your web page, so it's important to name it well.

Where does this title come from? View the source of your web page (usually with ctrl-U on Windows or cmd+alt-U on a Mac) to inspect the HTML:

<!DOCTYPE html>

The title is right there, but how did it get there? And where's all that other HTML coming from?

The Application File

In reality, a controller doesn't just return its associated template. Instead, Rails creates a complete HTML page by combining the specific page template with a general layout file. The default layout file is application.html.erb inside views/layouts. Open it up:

<!DOCTYPE html>
  <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>
  <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
  <%= csrf_meta_tags %>

<%= yield %>


You can see the standard HTML boilerplate above, including an area for the title. Below that there are some special Rails tags to include CSS and JavaScript files. Then there's the <body> element with <%= yield %> inside. This is where specific templates gets inserted into the layout.

End of Free Content Preview. Please Sign in or Sign up to buy premium content.

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