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 3 years have passed since last update.

find_by_**メソッドでレコードが見つからなかったときにで404ページを表示する

Last updated at Posted at 2020-05-04
route.rb
    match '/:code' => redirect('/information/%{code}'), via: [:get]
    match '*path' => 'front#render_404',via: [:get]

より、/pathできたものはinformationコントローラに行くようになっていて、showメソッドで精査するんだけど、現状500errorの画面が出てきているのをpage not found 404エラーを表示したい


  def show
    @information = Information.find_by_code(params[:code])
    gon.code = params[:code]
  rescue
    binding.pry
    render 'errors/404', status: :not_found
  end

こちらより、

findActiveRecord::RecordNotFoundと例外が吐かれるが
find_by_codeは検索メソッドなのでエラーではなくnilがかえる。

なので上記コードはrescueに引っかからない。

なので、nilのときは404エラーにレンダリングする形を取ってみる。


  def show
    @information = Information.find_by_code(params[:code])
    render 'errors/404', status: :not_found if @information.nil?
    gon.code = params[:code]
  end

解決

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?