Are redirect_to and render exchangeable?

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.

enter image description here

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.

enter image description here

So the place where redirect_to should 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, render is 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 render and redirect, you should read this article.

Leave a Comment

tech