Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails redirect how to pass params in routes file

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?

like image 661
ruevaughn Avatar asked Oct 16 '12 00:10

ruevaughn


2 Answers

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.

like image 116
ck3g Avatar answered Nov 03 '22 00:11

ck3g


You can do this in Rails 5.

match '/products/bracelets/:name/:name2', to: "/products/wristbands/%{name}/%{name2}"
like image 36
frediy Avatar answered Nov 02 '22 23:11

frediy