在 Ruby on Rails 中支持类似 /similar-to-:product 的 URL 吗?

发布于 2024-07-05 03:03:00 字数 350 浏览 9 评论 0原文

我一直在尝试使用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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

不交电费瞎发啥光 2024-07-12 03:03:00

一个简单的解决方案是使用路由过滤器。 有关详细信息,请参阅自述文件。

使用路由过滤器,您可以拥有一个 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.

梦境 2024-07-12 03:03:00

我有点困惑,但是你可以添加“to-”作为分隔符吗?

I'm a little confused, but could you maybe add "to-" as a seperator?

一片旧的回忆 2024-07-12 03:03:00

我会重构您的网址,使它们只是“与/产品相似”

I would refactor your URLs so that they're simply "similar-to/product"

桃酥萝莉 2024-07-12 03:03:00

事实上,您可以添加 - 作为分隔符,然后使用路由通配。

map.similar_product '/similar-to-*product', :controller => 'products', :action => 'similar'

然后,在 ProductsController#similar 中,

@product = Product.find_by_slug params[:product].join('-')

尽管重构看起来确实更好,因为使用这种方法,您需要专门处理所有可以包含连字符的 slugs。

In fact you can add - as a separator, then use route globbing.

map.similar_product '/similar-to-*product', :controller => 'products', :action => 'similar'

then, in ProductsController#similar

@product = Product.find_by_slug params[:product].join('-')

Though refactoring does seem nicer, since with this approach you'll need to specially handle all slugs that can contain hyphens.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文