如何从Rails路由中删除控制器名称? [英] How to remove controller names from rails routes?

查看:81
本文介绍了如何从Rails路由中删除控制器名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想缩减应用程序中的路由,以便:

I would like to trim down the routes on my application so that:

http://myapplication.com/users/peter/问题/如何创​​建网址

成为...

http://myapplication.com/peter/how-do-i-create-urls

I有一个用户控制器,希望它能提供足够的资源。用户还具有称为问题的嵌套资源。

I have a users controller and would like it to be resourceful. Users also have a nested resource called questions.

基本路线文件

没有任何URL修剪,路由文件如下所示:

Without any URL trimming, the routes file looks like this:

...
resources :users do
  resources :questions
end

然而,URL的格式为

http://myapplication.com/users/peter/questions/how-do-i-create-urls

而不是

http://myapplication.com/peter/how-do-i -create-urls

部分成功
我尝试执行以下操作:

Partial success I have tried doing the following:

...
resources :users, :path => '' do
  resources :questions
end

这有效并产生:

http://myapplication.com/peter/questions/how-do-i-create-urls

但是,如果我尝试:

...
resources :users, :path => '' do
  resources :questions, :path => ''
end

然后事情开始出错。

这是正确的方法吗?如果可以,是否也可以使其与嵌套资源一起使用?

Is this the right approach and if so, can it be made to work with nested resources too?

推荐答案

您的操作方式应该可以工作。我不知道您遇到了什么问题,但是如果您直接从应用中复制了示例代码,则可能是因为您在路线中添加了额外的 end 。可能看起来像这样:

The way you are doing it should work. I don't know what problem you are experiencing but if you copied the example code from your app directly then it might be because of the extra end that you have put in your routes. It should probably look like this:

resource :users, :path => '' do
  resource :questions, :path => ''
end

另一件事可能是起因,您需要有所不同注意的是,这些路由几乎捕获了所有请求,因此您应该将它们放在最后一个routes.rb中,以便其他路由最先匹配。以这种情况为例:

Another thing that could be the cause and that you need to be vary careful about is that these routes pretty much catches all requests and you should have them last in your routes.rb so that other routes matches first. Take this scenario for example:

resource :users, :path => '' do
  resource :questions, :path => ''
end

resources :posts

如果您这样做这样,那么就不会有任何请求被路由到Posts控制器,因为对/ posts / 1的请求将通过:user_id =>'posts',:id => 1

If you do it this way then no request will ever be routed to the Posts controller since a request to /posts/1 will be sent to the Questions controller with :user_id => 'posts', :id => 1

编辑:

此外,我现在注意到您使用资源而不是资源。不知道这是故意的还是错误的。

Also, I now noticed that you use resource instead of resources. Don't know if that is intended or if it is a mistake.

这篇关于如何从Rails路由中删除控制器名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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