November 6, 2010

Static Pages in Rails 3

If you’re here asking this question, you probably have the problem I had. You needed an “About Us” or “Privacy Policy” page, but you wanted to use the app’s layout to provide header and footer and nav and all that. I’m not sure it’s possible any longer to do this with just routes and no controller, but you can do it with a really minimal controller.

To do this, you:

  • Make a catchall route to route to your static pages
  • Make generic pages in app/views/static/
  • Create a skeleton controller to handle your views

Routes

First, you need to update your routes. Specifically, add a catchall to the bottom:

match 'static/:action', :controller => "static"

Views

After that, create some views in app/views/static (e.g. app/views/static/legal.html.erb)

Controller

Then, you need to create a controller like the following:

#file: app/controllers/static_controller.rb

class StaticController < ApplicationController

  def generic
    respond_to do |format|
      format.html
    end
  end

  def legal
    generic
  end

  def about
    generic
  end

This uses a generic method to just render to html.

Remember guys, I’ve been using Rails for like 2 days now. If you have a better way of doing this, say so!