简体   繁体   English

Rails路由使用绑定参数重定向

[英]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: 它不适用于%{ref},它返回:

"key{ref} not found" “找不到密钥{ref}”

How can i make this " ref " optional parameter in my redirect? 如何在重定向中使此“ ref ”可选参数?

Thanks. 谢谢。

You'll want to give your redirection route a default value for ref as well. 您还需要为您的重定向路由提供ref的默认值。 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'}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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