RESTful路由中的控制器名称可以是可选的吗? [英] Can controller names in RESTful routes be optional?

查看:60
本文介绍了RESTful路由中的控制器名称可以是可选的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用标准的 map.resource 路由机制和多个​​嵌套资源,生成的路由不必要地长。考虑以下路线:

With a standard map.resource routing mechanics and several nested resources the resultant routes are unnecessarily long. Consider the following route:

site.org/users/pavelshved/blogs/blogging-horror/posts/12345

routes.rb 中创建起来很容易,确保它遵循某种有益的路由逻辑。

It's easy to create in routes.rb, and I'm sure it follows some kind of beneficial routing logic. But it's way too long and also seems like it's not intended to be human-readable.

一个不错的改进是删除控制器名称,因此它看起来像:

A nice improvement would be to drop controller names, so it looks like:

site.org/pavelshved/blogging-horror/12345

清晰,简单,简短。 可能变得模棱两可,但就我而言,我不想将任何用户命名为用户。

Clear, simple, short. It may become ambiguous, but in my case I'm not going to name any user "users", for instance.

我尝试设置:as => ,但它会产生如下所示的路由: site.org//pavelshved//blogging-horror//12345 由标准助手生成它们时。

I tried setting :as => '', but it yields routes like this: site.org//pavelshved//blogging-horror//12345 when generating them by standard helpers.

是否可以通过这种方式映射资源,以使控制器名称变为可选?

Is there a way to map resources in such a way, that controller names become optional?

推荐答案

正在寻找资源的:path_prefix选项。

You're looking for the :path_prefix option for resources.

map.resources :users do |user|
  user.resources :blogs do |blog|
    blog.resources :posts, :path_prefix => '/:user_login/:blog_title/:id'
  end
end

将为这种形式的所有博客生成宁静的路由: site.org/pavelshved/bogging-horror/posts/1234 。您需要付出一些额外的努力才能使用url辅助程序,但是您自己的包装程序无法快速修复。

Will produce restful routes for all blogs of this form: site.org/pavelshved/bogging-horror/posts/1234. You'll need to go to a little extra effort to use the url helpers but nothing a wrapper of your own couldn't quickly fix.

唯一摆脱这种情况的方法网址中的部分文章带有命名路由,但是这些文章需要重复才能使内容更加宁静。并且在尝试使用路由助手时也会遇到同样的问题。

The only way to get rid of the posts part of the url is with named routes, but those require some duplication to make restful. And you'll run into the same problems when trying to use route helpers.

这篇关于RESTful路由中的控制器名称可以是可选的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆