ゆうなんとかさんの雑記帳的な。

Twitterで踊ったり音ゲーしたりしてるあの名前がよくわからない人が書いてるらしいよ。

404ページ、500ページのつくりかた

いくつかやりかたがあります。

1. 静的ファイルで十分な場合

public/404.html、public/500.htmlというファイルを置くだけです。ね、かんたんでしょ?

2. レイアウトを使いまわしたい場合

まずはconfig/routes.rbを修正します。

MyApplication::Application.routes.draw do
  match '*not_found' => 'application#render_404' #この行を追加
end

次にapp/controllers/application_controller.rbに修正を加えましょう。

class ApplicationController < ActionController::Base
  #以下のコードを追加
  rescue_from ActiveRecord::RecordNotFound,    :with => :render_404
  rescue_from ActionController::UnknownAction, :with => :render_404
  rescue_from ActionController::RoutingError,  :with => :render_404
  rescue_from Exception, :with => :render_500

  def render_404(exception = nil)
    render :template => "使いたいテンプレート", :status => 404, :layout => '使いたいレイアウト', :content_type => 'text/html'
  end

  def render_500(exception = nil)
    render :template => "使いたいテンプレート", :status => 500, :layout => '使いたいレイアウト', :content_type => 'text/html'
  end
end

これでOKです。レイアウトは省略するとデフォルトのものが使われます。

3.折衷的なやりかた

テンプレートで動的にやるのは大層でアレだけど、レイアウトは他のと同じのを使いたいなぁというときは1.と2.を組み合わせてやる感じでいけます。

  1. public/404.htmlとpublic/500.htmlの中身をメインコンテンツ部だけにします。
  2. 2.と同じようにルーティングを追加します。
  3. ApplicationController#render_404とApplicationController#render_500のrenderに渡す引数を以下のようにします。
  render :file => "#{Rails.root}/public/404.html", :status => 404, :content_type => 'text/html' # ApplicationController#render_404の場合

ここで:layout => falseとするとレイアウトをオフにできるので、1つ目のやりかたと同じような結果になります。

結構簡単に作れますね。せっかくなのでちょっとおもしろいエラーページを作ってみてもおもしろいかもしれませんね。
日本のWebサイトの404ページデザインいろいろ+α - かちびと.net