在 Ruby on Rails 中支持类似 /similar-to-:product 的 URL 吗?
我一直在尝试使用routes.rb 为我的网站创建一个URL /similar-to-:product (其中产品是动态的)。 问题是,routes.rb 很容易支持 /:product-similar 之类的 URL,但不支持前者,因为它要求 :product 前面有分隔符(“/”是分隔符,但“-”不是)。 分隔符列表位于 ActionController::Routing::SEPARATORS 中。
我无法添加“-”作为分隔符,因为 :product 也可以包含连字符。 支持这样的 URL 的最佳方式是什么?
我成功尝试过的一种方法是不使用 paths.rb 并将 URL 解析逻辑放在控制器本身中,但这不是最干净的方法。
I have been trying to use routes.rb for creating a URL /similar-to-:product (where product is dynamic) for my website. The issue is that routes.rb readily supports URLs like /:product-similar but doesn't support the former because it requires :product to be preceded with a separator ('/' is a separator but '-' isn't). The list of separators is in ActionController::Routing::SEPARATORS.
I can't add '-' as a separator because :product can also contain a hyphen. What is the best way of supporting a URL like this?
One way that I have successfully tried is to not use routes.rb and put the URL parsing logic in the controller itself, but that isn't the cleanest way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
一个简单的解决方案是使用路由过滤器。 有关详细信息,请参阅自述文件。
使用路由过滤器,您可以拥有一个 url
/similar-to-:product
,在路由识别之前将其预处理为/similar-to/:product
。 您还需要对从/similar-to/:product
到/similat-to-:product
的生成路径进行后处理。An easy solution is using a routing filter. See README for details.
With routing filter you can have a url
/similar-to-:product
, preprocess it to/similar-to/:product
before it gets to routing recognition. You'll also want to post-process generated paths back from/similar-to/:product
to/similat-to-:product
.我有点困惑,但是你可以添加“to-”作为分隔符吗?
I'm a little confused, but could you maybe add "to-" as a seperator?
我会重构您的网址,使它们只是“与/产品相似”
I would refactor your URLs so that they're simply "similar-to/product"
事实上,您可以添加
-
作为分隔符,然后使用路由通配。然后,在 ProductsController#similar 中,
尽管重构看起来确实更好,因为使用这种方法,您需要专门处理所有可以包含连字符的 slugs。
In fact you can add
-
as a separator, then use route globbing.then, in ProductsController#similar
Though refactoring does seem nicer, since with this approach you'll need to specially handle all slugs that can contain hyphens.