LoginSignup
1
0

More than 1 year has passed since last update.

renderとredirect_toによる画面遷移について

Posted at

概要

  • create、update、destroyアクションではビューファイルを作成しないことが多い
  • そのため上記のアクションで画面遷移先を決めるために、redirect_to, renderを用いる
  • 新規投稿, 編集, 削除した際は、以下のいずれかの方法で指定されたビューを表示させる

redirect_to

処理の流れ

  1. redirect_toがルーティングにURLを送る
  2. ルーティングと送られてきたURLとHTTPメソッドを照らし合わせて、どのコントローラのどのアクションを実行するかを決める
  3. アクションを実行する
  4. ビューを表示する

render

処理の流れ

  1. renderで定義したビューファイルを表示する

renderが裏で動いているのはたったこれだけです

違いと注意点

renderとredirect_toの大きな違いを一つあげるとすると、新たにアクションを実行するかしないかという点があります。

  • render
    アクションを新たに実行しない

  • redirect_to
    アクションを新たに実行する

使い分け

  • エラ〜メッセージを使う場合にはrenderを使う
  • それ以外はredirect_toを使う
def create

@post = Post.find(post_params)
    if @post.save
        redirect_to post_path(@post)
    else
        flash.now[:notice] = "投稿できませんでした"
        render :new
    end
end

・
・
・

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