Redirect all routes to another path and keep the rest of the URL intact

I want to rename a resource in a Rails application and redirect all old routes to new ones for backward compatibility with old links. For example, rename 'user' to 'member' and follow any arbitrary routes, such as example.com/user/1/posts/all?order=dateredirected toexample.com/member/1/posts/all?order=date

How to configure a file routes.rbto redirect all paths to another route, but keeping all path parameters after what I am looking to match (including URL parameters)?

It should also work, for example, for example.com/user/no/real/path?foo=bar, which should be redirected toexample.com/member/no/real/path?foo=bar

Basically I want to redirect any pathtopath.sub(/\A\/user/, '/member')

I checked this answer , but it does not work with parameters.

This is a solution that I'm still pretty terrible:

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
  }
+4
source share

Source: https://habr.com/ru/post/1524968/


All Articles