Patrick Berkeley Book Notes

Permalinks in Rails 3

How To Easily Create Pretty URLs

After reading a bunch of methods for creating nice URLs in Rails:

The following is a combination of Emilien Taque’s technique and Henrik’s method. Note that url_for’s :overwrite_params was deprecated in 2.3.6.

# app/models/page.rb
class Page < ActiveRecord::Base
  
  before_save do |page|
    page.permalink ||= page.title.parameterize
  end
  
  def to_param
    [id, title.parameterize].join("-")
  end

end
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  protect_from_forgery
  
  protected

  def redirect_if_moved(record, param_key = :id)
    redirect_to record, :status => 301 if record.to_param != params[param_key]
  end
end
# app/controllers/pages_controller.rb
class PagesController < ApplicationController
  respond_to :html, :xml
  
  # methods ...

  def show
    @page = Page.find(params[:id])

    redirect_if_moved @page and return
    respond_with @page
  end

  # methods ...

end
Fork me on GitHub