こんにちは。菜笑[なえ]です。
今回は「Rails ActionNotFound エラーの対応 404ページを表示させる」という内容で書いていきます。
目次
事象
Railsで存在しないページにアクセスしたら、404ページを表示させる。ということをやっている時のエラーです。
エラー内容
AbstractController::ActionNotFound (The action 'render_404' could not be found for ApplicationController):
コード状況
# 一番最後に
get '*path', controller: 'application', action: 'render_404'
class ApplicationController < ActionController::Base
private
# 例外処理
rescue_from ActiveRecord::RecordNotFound, with: :render_404
rescue_from ActionController::RoutingError, with: :render_404
def render_404
render template: 'static_pages/error', status: 404, layout: 'application', content_type: 'text/html'
end
end
解決方法
application_controller.rb
に書いてる処理を、private
から出してあげれば解決しました!
private
中に入ってるから、他からアクセスできなかったのが原因でした。
class ApplicationController < ActionController::Base
# 例外処理
rescue_from ActiveRecord::RecordNotFound, with: :render_404
rescue_from ActionController::RoutingError, with: :render_404
def render_404
render template: 'static_pages/error', status: 404, layout: 'application', content_type: 'text/html'
end
private
end
おわりに
最初は「定義してあるのになんでだ!」と思いましたが、冷静になって考えると「そりゃそうだ。」と気づけました。
ミスがなさそうなのに…。と思うときほど、焦らず冷静に処理を見ていきたいですね。