When I first started learning Rails, it took me a few weeks to figure out that Redirect and Render did different things. I overlooked them and figured that I’d throw one into my controller as needed and everything would be handled. Tubes on the Internet are all the same, right? Wrong.
Let’s start with Redirects. With a Redirect, Rails tells the browser to do a new HTTP request to that specific path. Your code stops running while your browser pushes you to a new page. With Render, you can load many different pieces of your view, from partials and error messages to forms or even entire pages, like a 404 error page.
In the code below, a user will create a new Lesson. A Lesson is like a tweet, it’s 140 characters or less containing what they learned that day. If the Lesson is between 1 and 140 characters in length, @lesson.save will work successfully and a new entry will be recorded in the database.
After that, the app will redirect itself back to the root path where I display a running list of all of the Lessons created, sorted by date. When Rails does a Redirect, by default it’s a 302 (or a temporary redirect) since your redirect only happens in certain cases, like when the app successfully submits and saves a Lesson.
@lesson = Lesson.new(params[:lesson])
But let’s say that our little Lesson doesn’t save. Bummer. Maybe you learned a lot that day. and couldn’t fit it all into 140 characters. Maybe you just pressed return and submitted the form by accident. You’ve now bumped up against Render.
Render is great because it’s so versatile. In this case, I render the new Lesson view. In my directories, the new Lesson view is located at /lessons/new.html.erb. Since I generated a Rails app quickly with a scaffold command, the code in that file is all pre-written for me by Rails to help out.
When Rails renders the new Lesson view, it will show me any errors that were made in the creation of my Lesson. It will also pre-fill the fields that a Lesson requires with the pieces that failed before so that I can reference the error for necessary changes that need to be made and make them directly below before I submit my new Lesson. That’s pretty handy and all built straight into Rails.
If you were to do a redirect_to root_path on the Lesson not saving, you wouldn’t know why the Lesson didn’t save, since in this code there’s no messaging telling you one way or another. Since this is a simple application, I fork the user experience here but what I’d rather do is bring the user back to the same page as they’d see on a successful Lesson entry but with rendered errors related to their Lesson so that they could give it another try without adding more routes through the app’s flow.
I hope this was helpful. If you have questions or comments, contribute to the discussion about this post on Hacker News.
I’d also be humbled if you followed me on Twitter.