LoginSignup
0
0

More than 3 years have passed since last update.

render と redirect_to の使い分け基準

Last updated at Posted at 2020-09-20

【概要】

1.結論

2.どのように使うか

3.なぜそのような違いが発生するのか

4.ここから学んだこと

1.結論

Controllerを挟みたくないか、一度挟みたいかです

2.どのように使うか

render

(i)ただViewファイルを指定して表示させたい

controller.rb
def
 render '***(Viewファイル名).index(アクション名) #---"a"
end

or

def
 render :index(アクション名) #---"b"
end

"a"と"b"の違いは
a➡︎違うコントローラーのアクションを表示させたい
b➡︎renderを記載している同コントローラーのアクションを表示させたい
ということになります。

(ii)複数のhtml.erbファイルで同じプログラムを使いたい

<%= render 'public/error_messages', model: f.object %> #---自分の記事から抜粋

上記の場合はindex,new,showアクションで空で入力した際に”必要事項が入力されていないよ!”メッセージを出しています。(エラーバンドリングの出し方)

redirect_to

(i)一度Controller処理を通したアクションを行いたい

controller
def
 redirect_to("/app/(Viewフォルダ名)/(アクション名.html.erb)")
end

or

def
 redirect_to ****_****_path
end

つまりURL指定ということです。

3.なぜそのような違いが発生するのか

結論は"もう一度Controller"が間に入っているかの違いになります。

❶renderはController➡︎Viewの動きに対して
❷redirect_toはController➡︎routes.rb(URLに基づいたid)➡︎Controller➡︎View
という動きになります。
renderだけだと”ただ”ページを表示するだけなので、処理に困りエラーが起きることがありました。
redirect_toはControllerを一回挟むのでupdate/destoryアクションをエラーなしで行えます。


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