I want to rename a resource in a Rails app, and have all the old routes redirect to the new ones for backwards compatibility with old links. For example, rename 'user' to 'member' and have all arbitrary route such as example.com/user/1/posts/all?order=date
redirected to example.com/member/1/posts/all?order=date
How can I set up the routes.rb
file to redirect all paths to another route, but maintaining all the path params after what I'm looking to match (including url params)?
It should also work, for example, for example.com/user/no/real/path?foo=bar
, which should redirect to example.com/member/no/real/path?foo=bar
Basically I want to redirect any path
to path.sub(/\A\/user/, '/member')
I checked out this answer, but it does not seem to work with the parameters.
This is the solution I have so far, pretty awful:
get 'user/*path', to: redirect{|params, request|
path = params[:path].sub('/user', '/member')
params = request.params.except(:path).map{|k,v| "#{k}=#{v}"}.join('&')
if params.presence
"#{path}?#{params}"
else
path
end
}