Rails: Static Pages Using the Controller Route Macro

One of my Rails apps recently took responsibility for serving the home page and marketing pages from an installation of Wordpress, mainly to allow for a site-wide nav bar which shows login status. Doing this in Rails is not rocket science, but after experimenting with a few different approaches this is the approach I think works best, along with an improvement to the status quo.

The idea is to put all the static pages in a PagesController which has a single action and corresponding view for each static page. So your homepage would have an index action and a corresponding index.html.erb view file. And your About Us page might be an about action with an about.html.erb view. And so on. Here's what it all looks like.

In your config/routes.rb:

App::Application.routes.draw do
  root to: "pages#index"
  get :contact, to: "pages#contact"
  get :about, to: "pages#contact"
end

In your app/controllers/pages_controller.rb:

class PagesController < ApplicationController
  def index
  end

  def contact
  end

  def about
  end
end

And then you just have a single view to match each action in app/views/pages/.

This is all fine and straightforward, but those route declarations really bothered me. They strike me as very repetitious, especially as you add more and more static pages, so I went digging through the Rails documentation and came across the controller route macro. It essentially scopes a bunch of routes to a specific controller. In other words, exactly what I was looking for.

Now your routes look like this:

App::Application.routes.draw do
  controller :pages do
    root to: :index
    get :contact
    get :about
  end
end

This solution is two lines longer, yet so much more concise. It nicely groups together a set of routes that are related to each other. I think the Rails route scoping documentation is worth a read if you find yourself repetitively adding the same controller value to a bunch of different routes.