Translate

November 9, 2011

render vs redirect_to in Ruby on Rails

Here's what you need to know when you're deciding between a render and a redirect_to in your controller action

render
This will render a particular view using the instance variables available in the action.
For example if a render was used for the new action, when a user goes to /new, the new action in the controller is called, instance variables are created and then passed to the new view. Rails creates the html for that view and returns it back to the user's browser. This is what you would consider a normal page load.

redirect_to
This will send a redirect to the user's browser telling it to re-request a new URL as 302 redirect response. Then the browser will send a new request to that URL and it will go through the action for that URL, oblivious to the fact that it was redirected to. None of the variables created in the action that caused the redirect will be available to the redirected view. This is what happens when you click on 'Create' in a form and the object is created and you're redirected to the edit view for that object.

If you do not have a render or a redirect_to in your controller method for a particular action then Rails will automatically render the template for that action. For example if your action is new, rails will render the view for new: new.html.erb.

If you need to render another action's view, you can use render :action_name.

If you need the user to run a new action, use redirect_to :action => :action_name. For example if the user has clicked 'Create' and there are no errors in creating the object, you can use redirect_to :action => :show to show the successfully created object.

Related posts:
Difference between update_attribute and update_column 
What is different in update_all, update,  update_attribute, update_attributes methods of Active Record
Difference between .nil?, .empty?, .blank?, .present? 
render vs redirect_to in Ruby on Rails

About

No comments: