Rails 2.3 中的自定义嵌套路由

发布于 2024-11-09 09:30:30 字数 391 浏览 0 评论 0原文

我正在尝试更改我正在处理的这个项目中的一些 URL,但我在任何文档中都找不到我正在寻找的内容的任何示例,并且我所有的尝试似乎最终都不起作用。

这就是我正在尝试做的事情。我有一篇包含多个图像的帖子,并且可以使用如下 URL 访问单个图像:

/posts/aliased_title/images/2

但是,我想更改它,以便我可以删除 URL 的“帖子”和“图像”部分,将其更改为其他内容例如/aliased_title/2

我知道如何为单个控制器执行此操作,但如何使用图像控制器来完成此操作?我可以通过生成“路径”(如 post_image_path)的方式来执行此操作,还是需要将每个操作硬编码到路由中?

先感谢您。

I'm trying to change some URLs in this project I'm working on, but I can't find any examples of what I'm looking for in any documentation and all my attempts seem to end up not working.

Here's what I'm trying to do. I have a post that has several images, and an individual image would be accessed with an URL like this:

/posts/aliased_title/images/2

However, I want to change it so I can remove the "posts" and "images" part of the URL, change it to something like /aliased_title/2.

I know how to do this for a single controller, but how can I accomplish this with the images controller as well? Can I do this in a way that will generate the "paths" (like post_image_path), or do I need to hard code every single action into the routing?

Thank you in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

寂寞美少年 2024-11-16 09:30:30

根据您的路线和别名标题的外观,您可以使用如下内容:

resources :images, :path => '/:title/:id', :constrain => { :title => /[a-z_-]+/ }

# in your view
image_path(image.title, image)

请记住,路线按照定义的顺序匹配,因此您需要将此行放在路线文件的底部,以便它不会干扰 /users/2 等路由。

综上所述,您应该认真考虑您的用例是否可以使用像 /image 这样的锚点。它将防止路由中出现很多令人困惑的问题,而这些问题很可能会发生往下咬你屁股。没有锚点并非不可行,但它确实会产生额外的工作。

Depending what your routes and aliased titles look like, you can use something like the following:

resources :images, :path => '/:title/:id', :constrain => { :title => /[a-z_-]+/ }

# in your view
image_path(image.title, image)

Keep in mind that routes match in the order they are defined, so you will want to put this line down at the bottom of your routes file so that it doesn't interfere with routes like /users/2.

All this said, you should strongly consider whether your use case can live with an anchor like /image. It'll prevent a lot of confusing problems with routing that will very likely bite you in the ass down the line. It's not infeasible to do without the anchor, but it does create additional work.

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