LuckyLuke LuckyLuke - 1 year ago 76
Ruby Question

Static pages in Ruby on Rails

What are the standard way of making a Ruby on Rails application that will have pages such as

  • Home

  • About

  • Contact

I would appricate if someone had links or an answers rather than just say use a gem because I want to learn how to make simple webapps with such behavior.

Answer Source

Depends on how you want to handle the content in those pages.

Approach #1 - store content in views

If you just want to put all your content in ERB views, then a very simple approach is to create a PagesController whose purpose is to deal with static pages. Each page is represented by one action in the controller.


class PagesController < ApplicationController
  def home

  def about

  def contact


match '/home' => 'pages#home'
match '/about' => 'pages#about'
match '/contact' => 'pages#contact'

Then create home.html.erb, about.html.erb, and contact.html.erb views under app/views/pages. These views contain whatever content you want on your static pages. They'll by default use your app's application.html.erb layout.

You'll also want to look into page caching to give yourself a boost in performance.

Approach #2 - store content in database

Another approach I've used is to make a very basic CMS for static pages. In this case, pages are represented in the model. It uses the friendly_id gem to handle slugs for each page so that they can be retrieved by a pretty name in the URL (e.g., /about) rather than by ID.


class Page < ActiveRecord::Base
  attr_accessible :title, :content

  validates_presence_of :title, :content

  has_friendly_id :title, :use_slug => true, :approximate_ascii => true


class PagesController < ApplicationController
  def show
    @page = Page.find(params[:id])
    render 'shared/404', :status => 404 if @page.nil?


<%= raw @page.content %>


match '/:id' => 'pages#show'

Note: put this entry at the end of routes.rb since it matches everything.

Then how you want to create, edit and update pages are up to you - you can have an admin interface, or build it in to your public interface somehow. This approach can benefit from page caching too.