Site icon Treehouse Blog

How to Create Static Pages in Rails

Have you ever wanted to create static pages in Rails? These are pages that don’t necessarily contain any dynamic info or pull from the database and don’t require an entire controller.

While some pre-built gems allow this to be done fairly quickly, it’s also good practice to roll your own. Let’s see how we can create some static pages in Rails using our own application.

Table of Contents

Rails Static Pages Setup

For the rest of this tutorial, I’m going to be using a Rails 4.2 application. These instructions should work in other versions of Rails but I’ve only tested against this version.

If you’d like to follow along, install the latest version of Ruby on Rails and skip ahead. If you don’t have Ruby on Rails installed, there are some great tutorials for OS X, Windows, and Ubuntu over on Treehouse that will get you up and running.

Generate a Pages Controller

Since we’re doing Rails static pages only, we don’t need to generate any models to interface with a database. You can either create a controller yourself or use Rails to generate one.

Either way, we’ll skip creating the CSS and JavaScript that go along with it. If you’d like to use Rails to generate a controller, run this command:

bin/rails generate controller pages --skip-assets

Alternatively, just create it yourself using the command line:

touch app/controllers/pages_controller.rb

And place the following in the app/controllers/pages_controller.rb file:

  class PagesController < ApplicationController
    def show
    end
  end  

That will set up an empty show action in our controller. The show action in the pages controller will be what we use to render our static page.

Now that we have a show action, we need to make it do something. We’re going to tell the show action to render a page template that is the same name as a parameter that is passed in.

We’re going to call the parameter page. We’re going to assume that the static page lives in the app/views/pages directory and has an extension of html.erb. Rails looks for that extension to render automatically, so we can leave it off.

Our show action will now look like this:

class PagesController < ApplicationController
  def show
    render template: "pages/#{params[:page]}"
  end
end

With the show action all set up, we can move on to the routes.

Create a Route

The route is really easy and is just a single entry in our routes.rb file:

Rails.application.routes.draw do
  get "/pages/:page" => "pages#show"
end

This will send every url that matches /pages/ to our pages controller we created above. Any of the following would now work:

Based on the controller we created above, we now have to place our static pages in the app/views/pages directory and they will show up.

Create a Static Page

Creating static pages in Rails is very easy with the above setup. Just create the file in your terminal (or text editor):

touch app/views/pages/about.html.erb

Now fill it with some content. I’ve chosen to use some cupcake ipsum text because cupcakes are delicious. Save the file and head over to http://localhost:3000/pages/about and you should see the following:

It works! Awesome! This is a great start.

A Static Home Page

It may be a requirement for your application to have a static home page with no dynamic content. That’s simple to add to our current setup. First, we’ll need to create the home page.

Place the following in app/views/pages/home.html.erb.


  <h2>Home Page</h2>

  <p>This would be a static home page in a Rails application.</p>

This is just a place holder. Your real content can go in there later. Next, we’ll tell Rails to look for that as the default root page.

We do that by passing in the page parameter to the root route directive. Now we just have to add the following to config/routes.rb, just before the closing end keyword:

root "pages#show", page: "home"

Now when you go to http://localhost:3000 you should see the following:

If you see the following screen, you may have named it something other than app/views/pages/home.html.erb:

Double check that for errors and reload the page.

Handling Not Found Errors in Rails Static Pages

We have basic static page rendering set up but we haven’t planned for what happens when someone hits a page that doesn’t exist.

We need to tell the visitor that the page is not found, and we’d be good net citizens to return a 404 status code as well. We can handle all of this in the pages controller.

In order to do all of that, we’ll create a method called valid_page? that checks to make sure the page actually exists in our Rails application where we expect it to.

The method exist? on the File class will return true or false if the file actually exists in that spot in the file system. We’ll pass that method an instance of the PathName class which has the full path of the requested template file on disk. The whole method will return true or false if the file exists.

From there, all we need to do is render a not found page if the file doesn’t exist. A default Rails application will have a 404 page in the public directory, so we can just use that. We’ll also send down a 404 status with the :not_found symbol. Here’s what the pages controller now looks like:

class PagesController < ApplicationController
    def show
      if valid_page?
        render template: "pages/#{params[:page]}"
      else
        render file: "public/404.html", status: :not_found
      end
    end

    private
    def valid_page?
      File.exist?(Pathname.new(Rails.root + "app/views/pages/#{params[:page]}.html.erb"))
    end
  end

Now if we go a nonexistent page, we should see the following:

Rails Static Pages, Slightly Enhanced

The Rails static pages are now all set up but we’ve decided to throw some marketing pages in to show off some of our application’s features.

Marketing wants us to put these at /pages/features/one, /pages/features/two, and so on. This is easy enough and only requires a small change in our code. Open up the routes and change this:

get "/pages/:page" => "pages#show"

To this:

get "/pages/*page" => "pages#show"

That small change will pass the page parameter in as an array. We can now create a features directory in app/views/pages and place our new feature pages in there. Here’s an example of features/one:

Learn more Ruby on Rails methods: How to Use the “each” Method in Ruby on Rails | Treehouse Quick Tip

One more neat thing is that we have access to Ruby’s methods in these pages. We don’t want to go crazy, but a few little calls here and there aren’t too much of an issue.

For example, if we wanted to add the current year to our home page, we could place the following in the page:

<p>© <%= Date.today.year %> My App.</p>

Which would render the following:

Related Reading: Using Select2 with Ruby on Rails

Learn More About Rails Static Pages With Treehouse

This is just one quick way to implement your own static pages in Rails. If you want to learn more about Ruby on Rails, Treehouse offers a wide range of courses that are chock full of tips and tricks. Sign-up for a free trial of Treehouse today!

Exit mobile version