6

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
  }
Community
  • 1
  • 1
Nicolas
  • 2,297
  • 3
  • 28
  • 40

1 Answers1

0

I hope this solution would be helpful.

get 'user/*path', to: redirect{| _params, request| request.url.sub('user', 'member')}
Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
Rq Bhatti
  • 1
  • 3
  • Remember that Stack Overflow isn't just intended to solve the immediate problem, but also to help future readers find solutions to similar problems, which requires understanding the underlying code. This is especially important for members of our community who are beginners, and not familiar with the syntax. Given that, **can you [edit] your answer to include an explanation of what you're doing** and why you believe it is the best approach? – Jeremy Caney Apr 06 '23 at 00:17