0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rails3.2で404ページを使う

Last updated at Posted at 2019-10-31

きっかけは、削除したIDを探したときに表示される「ActiveRecord::RecordNotFound」がかっこ悪いから。

各コントローラーで対処

findよりfind_by_idでActiveRecord::RecordNotFoundを回避するを参考にして

hoge_controller.rb
# @hoge = Hoge.find(params[:id])
@hoge = Hoge.find_by_id(params[:id])

find_by_idで、見つからなければnilになる

hoge_controller.rb
@hoge = Hoge.find_by_id(params[:id])

if @hoge 
 (あったときのアクション)
else
 render :template => '/common/error_404'
end

動いたけど、これを全部でやるのはめんどくさい。

ActionControllerで対処

Rails3で404エラー画面作成
ひとまとめにできるので、こっちに切り替えた

renderに変数を渡したい。
参考:render先に変数が上手く渡らないときに確認すること

application_controller.rb
# rescue_from ActionController::UnknownAction, :with => :error_404
rescue_from ActiveRecord::RecordNotFound, :with => :error_404

def error_404(exception = nil)
  @ex = exception
  render :template => '/common/error_404', ex: @ex, :status => 404 
end

ActionController::UnknownActionで存在しないアクションが引っかからないのでコメントアウトした。
参考:uninitialized constant ActionController::UnknownAction (NameError) when starting the web server

error_404.html.erb
<%- if @ex %>
<p><%= @ex %></p>
<%- end %>

<%- if params[:id] %>
	<p>すまん、「ID<%= params[:id] %>」は見つからんかった</p> 
	<%= image_tag("cat.jpg")%>
<%- else %>
	<p>そんなページはありゃーせんのじゃー</p>
	<%= image_tag("dog.jpg")%>
<%- end %>

エラーの「ActionNotFound」「RecordNotFound」を記述したいけど、取り出し方がわからなかった。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?