简体   繁体   中英

Rails routes redirect with Bound Parameters

In my routes im doing:

get 'category/products/:product_hash(/:ref)',
  to: redirect('/new_path/products/%{product_hash}%{ref}', status: 301)

get 'new_path/products/:product_hash(/:ref)',
  to: 'products#new', as: :new_product, defaults: {ref: 'print'}

It isn't working with %{ref}, it returns:

"key{ref} not found"

How can i make this " ref " optional parameter in my redirect?

Thanks.

You'll want to give your redirection route a default value for ref as well. Note that empty string is a valid value, if you want the default to be blank.

You might also want to move the / outside the brackets - it's fine to have a trailing slash, and moving it will help to ensure that your defaults are passed through correctly (ie otherwise you would need to append the / , and there may be cases where you end up with a double slash). So you could end up with something like:

get 'category/products/:product_hash/(:ref)',
  to: redirect('/new_path/products/%{product_hash}/%{ref}', status: 301), defaults: {ref: ''}

get 'new_path/products/:product_hash/(:ref)',
  to: 'products#new', as: :new_product, defaults: {ref: 'print'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM