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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With