0
0
RailsHow-ToBeginner · 3 min read

How to Redirect in Routes in Ruby on Rails

In Ruby on Rails, you can redirect in routes using the redirect method inside your config/routes.rb file. This method sends users from one URL to another without needing a controller action. For example, get '/old', to: redirect('/new') redirects requests from '/old' to '/new'.
📐

Syntax

The basic syntax to redirect in Rails routes uses the redirect method inside the routing DSL. You specify the HTTP verb, the original path, and then use to: redirect('target_path') to define where to send the user.

  • get '/old_path', to: redirect('/new_path'): Redirects GET requests from '/old_path' to '/new_path'.
  • You can use string paths or named routes inside redirect().
  • Supports dynamic segments and query parameters.
ruby
get '/old_path', to: redirect('/new_path')
💻

Example

This example shows how to redirect from an old URL to a new one directly in the routes file. When a user visits '/home', they will be redirected to '/dashboard'.

ruby
Rails.application.routes.draw do
  get '/home', to: redirect('/dashboard')
  get '/dashboard', to: 'pages#dashboard'
end
Output
Visiting '/home' redirects the browser to '/dashboard', which loads the PagesController's dashboard action.
⚠️

Common Pitfalls

Common mistakes include:

  • Using redirect_to instead of redirect in routes (the former is for controllers).
  • Not specifying the HTTP verb, which can cause unexpected behavior.
  • Forgetting that redirects in routes are permanent (HTTP 301) by default, which may be cached by browsers.
ruby
get '/old', to: redirect_to('/new') # ❌ wrong in routes

# Correct way:
get '/old', to: redirect('/new')
📊

Quick Reference

UsageDescription
get '/old', to: redirect('/new')Redirect GET requests from '/old' to '/new'
redirect('/new', status: 302)Redirect with HTTP status 302 (temporary)
redirect { |params, req| "/users/#{req.params[:id]}" }Dynamic redirect using a block
root to: redirect('/welcome')Redirect root URL to '/welcome'

Key Takeaways

Use redirect inside routes to send users from one URL to another without a controller.
Always specify the HTTP verb like get when defining redirects in routes.
Redirects in routes default to permanent (301) status; specify status: 302 for temporary redirects.
Do not use redirect_to in routes; it belongs in controllers.
You can use dynamic redirects with blocks to customize target URLs based on request parameters.