How to Use redirect_to in Ruby on Rails

09/19/2021

Contents

In this article, you will learn how to use the redirect_to method in Ruby on Rails.

How to use redirect_to

In Ruby on Rails, the redirect_to method is used to redirect a user to a new URL. This is useful for things like redirecting after a form submission or when a user logs in.

Here’s an example of how to use redirect_to in a Rails controller action:

def create
  # save the new record
  @user = User.new(user_params)
  if @user.save
    # redirect to the user's profile page
    redirect_to user_path(@user)
  else
    # show the new user form again with errors
    render :new
  end
end

In this example, we have a create action in a controller that handles creating a new user. If the user is successfully saved, we redirect to their profile page using redirect_to user_path(@user). The user_path helper method generates a URL for the user’s profile page based on their ID.

If there are validation errors when creating the user, we render the new view again with errors so the user can correct them.

You can also use redirect_to with a URL string instead of a helper method:

redirect_to "http://example.com"

In this case, the user will be redirected to the example.com website.

redirect_to can also take an optional second parameter, which is an options hash that can include things like a flash message:

redirect_to user_path(@user), notice: "User successfully created!"

In this example, we’re passing the notice option to redirect_to, which will display a flash message on the next page that the user sees after the redirect.