我想减少我的应用程序中的路由,以便:
myapplication/users/peter/questions/how-do-i-create-urls
变成……
myapplication/peter/how-do-i-create-urls
我有一个用户控制器,希望它足智多谋.用户还有一个称为问题的嵌套资源.
基本路线文件
没有任何 URL 修剪,路由文件如下所示:
...资源:用户做资源:问题结尾然而,这里的 URL 采用
的形式myapplication/users/peter/questions/how-do-i-create-urls
而不是
myapplication/peter/how-do-i-create-urls
部分成功我尝试过以下操作:
...资源:用户,:路径=>'' 做资源:问题结尾这有效并产生:
myapplication/peter/questions/how-do-i-create-urls
但是,如果我尝试:
...资源:用户,:路径=>'' 做资源:问题,:路径=>''结尾然后事情开始出错.
这是正确的方法吗?如果是,是否也可以使用嵌套资源?
解决方案你的做法应该行得通.我不知道您遇到了什么问题,但如果您直接从您的应用中复制示例代码,那么可能是因为您在路线中添加了额外的 end.它应该看起来像这样:
资源 :users, :path =>'' 做资源:问题,:路径=>''结尾另一个可能是原因并且您需要注意的事情是这些路由几乎可以捕获所有请求,您应该将它们放在您的 routes.rb 中,以便其他路由首先匹配.以这种情况为例:
资源 :users, :path =>'' 做资源:问题,:路径=>''结尾资源:帖子如果您这样做,则不会将任何请求路由到 Posts 控制器,因为对/posts/1 的请求将通过 :user_id => 'posts', :id => 1
另外,我现在注意到您使用资源而不是资源.不知道这是故意的还是错误的.
I would like to trim down the routes on my application so that:
myapplication/users/peter/questions/how-do-i-create-urls
becomes...
myapplication/peter/how-do-i-create-urls
I have a users controller and would like it to be resourceful. Users also have a nested resource called questions.
Basic routes file
Without any URL trimming, the routes file looks like this:
... resources :users do resources :questions endHowever the URLs from this take the form of
myapplication/users/peter/questions/how-do-i-create-urls
rather than
myapplication/peter/how-do-i-create-urls
Partial success I have tried doing the following:
... resources :users, :path => '' do resources :questions endThis works and produces:
myapplication/peter/questions/how-do-i-create-urls
However if I try:
... resources :users, :path => '' do resources :questions, :path => '' endThen things start to go wrong.
Is this the right approach and if so, can it be made to work with nested resources too?
解决方案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 => '' endAnother 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 :postsIf 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
Edit:
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 路由中删除控制器名称?
发布评论