LoginSignup
250
207

More than 3 years have passed since last update.

【Rails】renderとredirect_toの違いと使い分け

Last updated at Posted at 2018-10-12

renderとredirect_toの挙動が似ていて、混同しがちだったので
調べたものをまとめておきます。

renderとredirect_toの違い

・render     : 表示させるviewファイルを指定
・redirect_to   : URL(HTTPリクエストメソッド)を指定

renderは("フォルダ名/viewファイル名")

user_controller.rb
def
 render("user/edit")
end

redirect_toは("/URL/〜/〜/”)

user_controller.rb
def
 redirect_to("/app/posts/new")
end

renderとredirect_toの動き方の違い

・render     : controller → view
・redirect_to   : controller → URL → route → controller → view

redirect_toの方がちょっと遠回りしてますね。

renderがviewファイルを指定して、それを表示させるだけの処理に対して
redirect_toはブラウザ上でHTTPリクエストを受けたのと同じ処理がされます。

renderとredirect_toの使い分け

そのページに移る際に、
1.データの更新/削除、inputやformなど何かデータを送る処理
2.ログインなどの成否判断の処理
が行われているかで使い分けができます。

上のような処理が必要な場合には、

HTTPリクエストがPOSTの可能性が高い&適切なcontrollerの処理が要求される

為、redirect_toを使用します。

・render     : ログインや入力形式に失敗した場合など = ただエラーを表示させるだけ
・redirect_to   : データ更新/削除が必要な場合      = controllerの処理が必要

参考サイト

RailsGuide
https://railsguides.jp/layouts_and_rendering.html#redirect-to%E3%82%92%E4%BD%BF%E7%94%A8%E3%81%99%E3%82%8B
https://railsguides.jp/layouts_and_rendering.html#render%E3%82%92%E4%BD%BF%E7%94%A8%E3%81%99%E3%82%8B

render と redirect の違い
https://qiita.com/january108/items/54143581ab1f03deefa1

railsのrenderとredirect_toの違い
https://qiita.com/1ulce/items/282cccba1e44158489c8

【Rails】redirect_toとrenderの使い分け
https://qiita.com/jumpyoshim/items/ed10721c26963abdf121

250
207
6

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
250
207