For the code below, what happens if replacing redirect_to with render or vise verse?
def create
@product = Product.new(params[:product])
respond_to do |format|
if @product.save
format.html { redirect_to(@product, :notice => 'Product was successfully created.') }
else
format.html { render :action => "new" }
end
end
end
It seems OK replacing one with the other in code above. Is there a place where only redirect_to or render has to be used? Render does nothing but rendering a view. Redirect_to sends 302 request to server and current parameters are lost after redirecting.
Thanks.
If you’re using
render, when the user refreshes the page, it will submit the previous POST request again. This may cause undesired results like duplicate purchase and others.But if you’re using
redirect_to, when the user refreshes the page, it will just request that same page again. This is also known as the Post/Redirect/Get (PRG) pattern.So the place where
redirect_toshould be used is when you’re doing a HTTP POST request and you don’t want the user to resubmit the request when it’s done (which may cause duplicate items and other problems).In Rails, when a model fails to be saved,
renderis used to redisplay the form with the same entries that was filled previously. This is simpler because if you use redirect, you’ll have to pass the form entries either using parameters or session. The side effect is that if you refresh the browser, it will try to resubmit the previous form entries. This is acceptable because it will probably fail the same way, or if it’s successful now, it was what the user should expect in the first place anyway.For more in depth explanation about
renderandredirect, you should read this article.