LoginSignup
0
0

More than 3 years have passed since last update.

Railsのredirect_toとrenderについて

Last updated at Posted at 2020-12-08

renderとは

viewだけが返される処理

redirect_toとは

アクションを行う処理(viewも返される)

状況

  • 投稿ができるフォームとコントローラーが存在している。
投稿フォーム(new.html.erb)

スクリーンショット 2020-12-08 2.40.32.png

コントローラー(posts_controller.rb)
class PostsController < ApplicationController

 def index
   @posts = Post.all
 end

 def new
    @post = Post.new
 end

 def create
   @post = Post.new(post_params)

   if @post.save
     redirect_to posts_path
   else
     render :new
   end

   def post_params
     params.require(:post).permit(:title, :content)
   end

end

※post.rbにはvalidates :title, presence: trueを設定。(タイトルが空白の時は投稿ができない)

解説

titleが空じゃなかった場合

投稿することができるので、createアクションのif @post.saveはtrueとなり、redirect_to posts_pathが選ばれる。redirect_toではアクションが実行されるため、posts_pathに対応するindexアクションが実行される。

titleが空だった場合

投稿することはできないので、createアクションのif @post.saveはfalseとなり、render :newが実行される。renderではアクションが実行されずviewだけが返されるため、newアクションは実行されず、newアクションに対応したnew.html.erb(view)が返される。

renderとインスタンス変数

結論 renderの記述をしているアクションには、render先で記述しているアクションのインスタンス変数を持っていなければエラーが出るので注意すべき。

解説のtitleが空だった場合の例の場合ではcreateアクションの中にいて、viewだけがnew.html.erbを返している事になる。 この場合のインスタンス変数はcreateにある@postが使われている。仮にcreateに@postが存在しない場合に、render :newを返すとどうなるだろうか?
本来viewで使われている@postが存在しないため、new.html.erbが表示できずエラーとなってしまう。

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