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.

[Rails]ページが見つからない時に指定のページにレンダリングする

Posted at

はじめに

例えば記事投稿アプリケーションなどで削除された記事に飛んだ場合に「指定されたページは存在しません」みたいなことってよくあると思います。
※以下Twitterから引用

2020-01-07_08h05_27.png

今回は指定された記事がない場合のレンダリング方法について解説します。

環境

Ruby 2.6.3
Rails 6.0.3

本題

まずは見つからないページを指定された場合のルーティングを作成します

routes.rb
get "posts/post_deleted" => "posts#post_deleted"

次にビューに記述していきます

<p>このページは存在しません<p>

次にコントローラーに記述しますが、今回は特定の記事にアクセスした時の処理なのでshowアクションにコードを追加していきます。

posts_controller.rb
def show
  @post = Post.find_by(id: params[:id])
  if @post == nil
     render "posts/post_deleted"
     return
  end
end

def post_deleted
end

以上で実装が完了です。
スクリーンショット 2021-07-04 0.44.49.png

もっと良い方法があるなどあればメッセージをいただけると幸いです

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?