Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

redirect_to vs. render - Michael Hartl's tutorial

Going through Hartl's tutorial, at Listing 10.42 in microposts controller we have

  def create
    @micropost = current_user.microposts.build(micropost_params)
    if @micropost.save
      flash[:success] = "Micropost created!"
      redirect_to root_url
    else
      @feed_items = []
      render 'static_pages/home'
    end
  end

so in else branch we need to put empty @feed_items because render itself doesnt provide the variable.

My question is - why not use redirect_to root_url just like in if branch, that way this variable would be provided by controller action?

like image 408
tonino.j Avatar asked Oct 01 '22 02:10

tonino.j


1 Answers

If @micropost.save returns false, it means your @micropost is not valid. In other words: you have validations errors. These errors can be accessed through @micropost.errors. You should display them in the view, so the user knows what he's done wrong. If you redirect it will be a completely new request and @micropost.errors won't be available anymore. That's why he's using render.

Another aspect of this is that you'll want to repopulate the form with the values the user inputted. If you redirect these values will also be gone. To preserve the errors and posted values through a redirect you'd have to save them in a session or something. It's much easier to just render the view instead.

like image 152
Mischa Avatar answered Oct 03 '22 10:10

Mischa