LoginSignup
1
0

More than 5 years have passed since last update.

RubyOnRailsで.pngや.jpgへのエラー対応

Posted at

エラー内容

本来404エラーが返ってきたら、rescue_fromで404に飛ばしているが
/~.pngや/~.jpgにアクセスすると

Missing template errors/error_404 with {:locale=>[:ja], :formats=>[:png], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}. 

そんなテンプレートないよって言われる

原因

  • .pngにアクセスした場合、formats=>[:png]になる
  • 今回はErrorsControllerからerrorファイルを探しているがデフォルトのformatsは.html.erb
  • そして.pngなんてもちろんviews/errorにない。ゆえにmissing templateと怒られた。

対策

application_controller.rbに以下を書いて

def check_formats
    respond_to do |format|
      format.html { return true }
      format.all { render nothing: true, status: 404 and return false }
    end
  end

controllerにある全てのrenderに対して

render 'index', layout: 'top_layout' if check_formats

と記入することで対応で大丈夫か。みんなどうしてるんだろう。

参考

*stackoverflow
* Github

1
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
1
0