Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails routes redirect for query string

I have a problem, recently the name of a controller changed.

I changed the routes file to accept calls using the old controller name, for people with bookmarks referencing the old name:

get '/old/about', to: redirect('/new/about')
get '/old/report/:client', to: redirect('/new/report/%{client}')
get '/old/:sub_path', to: redirect('/new/%{sub_path}')

that works fine. But for calls with query string it blocks it to /report/200. for example:

/old/report/200?c_id=257&end=2013-10-19&num_results=294540&start=2013-10-13

it cuts the url to:

old/report/200

and shows me an error because of the lack of parameters. Do you know what can I do? (I thought the :sub_path line in the routes would help but not) :(

like image 883
Alejandra Avatar asked Oct 23 '13 18:10

Alejandra


2 Answers

Building on Alejandra's answer, more verbose but without the ? if there's no query string:

get "/old/report/:client", to: redirect{ |params, request| ["/new/report/#{params[:client]}", request.query_string.presence].compact.join('?') }

So /old/report/:client?with=param will become /new/report/:client?with=param, and /old/report/:client will become /new/report/:client.

like image 153
ben Avatar answered Sep 22 '22 13:09

ben


Modify redirect to use the path: option to preserve the querystring:

- get '/old/about', to: redirect('/new/about')
+ get '/old/about', to: redirect(path: '/new/about')

This is demonstrated in the API docs for redirect, see http://api.rubyonrails.org/classes/ActionDispatch/Routing/Redirection.html#method-i-redirect

like image 40
Eliot Sykes Avatar answered Sep 24 '22 13:09

Eliot Sykes