1
0

redirectとrenderの違い

Last updated at Posted at 2023-11-03

はじめに

何番煎じか分かりませんが、業務の中で気になって色々調べて整理することができたので記事にまとめます。

共通点としては、どちらも特定のコントローラーのアクションから、別のアクション(画面)をひっぱりだしたいときに使用します。

redirect_to

処理が成功したあと、画面遷移を行いたい場合に使用します。
GETのHTTPリクエストを送ります。
コントローラーを経由します。

test_controller.rb
def test
 redirect_to tests_url
end

render

処理が失敗したあと、エラーメッセージなどを表示する場合に使用します。
コントローラーを経由しません。

test_controller.rb
def test
 render :new
end

役立つかもしれない豆知識

renderする際は、インスタンス変数を再宣言しないといけない。

コントローラーを経由しないためです。
render先で値を表示するには、render前に値を取得しておく必要があります。

test_controller.rb
def new
 @test = Modeldata.find(1)
 render :new
end

def create
 # ここで@testを取得しないと、render時に@testを表示できない
 @test = Modeldata.find(1)
 render :new
end

redirect_to後の画面にフラッシュメッセージを表示したい。

少し工夫が必要。
下記のやり方ではフラッシュメッセージが表示できない。

test_controller.rb
def create
 flash.now[:notice] = "投稿に失敗しました"
 redirect_to action: :new
end

flash.keepを使えば可能。

test_controller.rb
def create
 flash[:notice] = "投稿に失敗しました"
 flash.keep(:notice)
 redirect_to action: :new
end

参考

https://qiita.com/morikuma709/items/e9146465df2d8a094d78
https://zenn.dev/yukihaga/articles/fda5528484865c

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