1
0

More than 3 years have passed since last update.

redirect_toとrenderの違い・使い分け ❏Rails❏

Last updated at Posted at 2019-12-01

【結論】アクションを実行するかしないかの違い

xxx_controller.rb
def create
  message = Message.new(message_params)
  if message.save
    redirect_to :new
  else
    render :new
  end
end

このようなcreateアクションがあります。

saveが成功した場合はnewアクションが実行され、一度ページがリセットされnewのページが表示されます。

saveが失敗した場合はnewアクションを通さず、入力された情報はそのままにnewのページが表示されます。



保存が成功したらフォームに情報を残しておく必要はありませんよね。
保存が失敗したらエラーメッセージを表示するなどして、入力情報のエラー部分のみを変更してもらいましょう。



参考

https://www.pikawaka.com/rails/render



ではまた!

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