ruby-on-railsroutes

Why redirect in the routes file?


Reading the Ruby on Rails guide, I see this example:

get '/stories/:name', to: redirect('/articles/%{name}')

And I'm confused, when would this be helpful? Couldn't you just point the path to the controller/action like this?

get '/stories/:name', to: 'articles#show'

Solution

  • They do very different things.

    get '/stories/:name', to: redirect('/articles/%{name}')
    

    Will result in the router responding directly with:

    HTTP/1.1 301 Moved Permanently
    Location: http://localhost:3000/articles/a_tall_tale
    

    This is useful if you want to redirect requests for a legacy route to the new route and tell clients to use the new URL but don't you're not able (or too lazy) to set up a redirect on the HTTP server layer (which has even less overhead).

    get '/stories/:name', to: 'articles#show'
    

    Will dispatch the request to the controller in question and send whatever response it generates to the client.

    If the goal is to support a legacy URL this won't actually tell clients to use the new URL unless you redirect from the controller and doing so would be less efficient than just doing it from the router.