Ruby on Rails redirect how to pass params in routes file

与世无争的帅哥 提交于 2020-01-13 13:09:35

问题


We recently changed the product name on our website from 'bracelets' to 'wristbands' and need to keep the old routes around for SEO purposes.

Essentially, these routes

www.hostname.com/products/bracelets/series-1/
www.hostname.com/products/bracelets/series-1/small-purple

should route to

www.hostname.com/products/wristbands/series-1/
www.hostname.com/products/wristbands/series-1/small-purple

I am reading the tutorial here http://guides.rubyonrails.org/routing.html#redirection and looks like i'll be using the block syntax, but am still not sure how to do the route properly. I'm looking to learn more about the routes file as well, so any information would be great. Thanks in advance

match "/bracelets/:name" => redirect {|params| "/wristbands/#{params[:name]}" }

EDIT:

OK i've been playing with it for a bit, and here is how it is working with what I have tried

match "/products/bracelets/:name/:name2" => redirect {|params| "/products/wristbands/#{params[:name].pluralize}/#{params[:name2].pluralize}" }

Input URL: localhost:3000/products/bracelets/series-1/small-purple

Output URL: localhost:3000/products/wristbands
Error Message: Invalid Product: series-1
(So the match worked, but the redirect didn't)

If I change the match to inspect params like this:

match "/products/balance-bracelets/:name/:name2" => redirect {|params| "/products/wristbands/#{params.inspect}" }

I get the following:

 /products/wristbands/{:name=>"series-1", :name2=>"small-purple"}

So it appears it isn't recognizing the second slash '/' or something. Any Ideas?


回答1:


I'm was at the same situation and that works for me:

match "/products/bracelets/:name/:name2" => redirect {|params, request| "/products/wristbands/#{params[:name].pluralize}/#{params[:name2].pluralize}" }

I've passed two agruments into the block.




回答2:


You can do this in Rails 5.

match '/products/bracelets/:name/:name2', to: "/products/wristbands/%{name}/%{name2}"


来源:https://stackoverflow.com/questions/12906097/ruby-on-rails-redirect-how-to-pass-params-in-routes-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!