Render Vs. Redirect_to in Rails

New to Rails and poking around a controller. You are bound to come across the methods render and redirect_to.

render ‘new’

redirect_to root_path

If you are wondering, “what is the difference between the two and how do I know when it is appropriate to use either?” this is the right place to be : D

Cheers to you for being so resourceful!

Render pulls the specified view and fills it in with the current information set while redirect_to hits the specified controller action.

Consider the following snippet for a user create action:

def create
  @user = User.new(params[:user])
  if @user.save
    sign_in @user
    flash[:success] = "Welcome to RideSociable. Your carriage awaits."
    redirect_to @user
  else
    @sub_title = "Sign up"
    render 'new'
  end
end

Note: in rails “redirect_to @user” is equivalent to “redirect_to user_path(@user)”

In this case redirect_to hits the user#show action in the users controller. The show action can then run code and set various variables (ex: “@user = User.find(params[:id])”) and render the show view users the variables it sets. render, by contrast, does not trigger the user#new action. It merely renders the ‘new’ view using the parameters set in the current action.

Why use render in this case?

The user has not provided valid credentials and cannot be added to the database. The user must fill out the form again. You can do one of two things:

  1. give the user a new blank form to fill out
  2. give the user a new form with most of their data filled in

Option two is much more user friendly and doesn’t discourage a potential user from signing up. Go with that one. @user has pulled all the data from the users submitted form. If you redirect_to the new_user_path to return the user to the form you will not have access to any of the data you just pulled from the form using “@user = User.new(params[:user])”. If you use render, you will pull the specified view using the variables you just defined, pre-filling in the form with most of the data the user needs.

render uses the currently defined instance variables and specifies a view to render

redirect_to sends a new request to the browser. It hits a new controller action and sets new variables.

Let me know if anything was unclear. Hope this was helpful.

David

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s