如何从Rails路由中删除控制器名称?

编程入门 行业动态 更新时间:2024-10-27 04:24:17
本文介绍了如何从Rails路由中删除控制器名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

myapplication/users/peter/问题/如何创​​建网址

成为...

myapplication/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的格式为

myapplication/users/peter/questions/how-do-i-create-urls

而不是

myapplication/peter/how-do-i -create-urls

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

Partial success I have tried doing the following:

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

这有效并产生:

myapplication/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路由中删除控制器名称?

本文发布于:2023-10-26 10:55:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1529933.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:路由   控制器   名称   Rails

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!