自定义路由和资源路由

发布于 2024-10-19 18:14:44 字数 420 浏览 6 评论 0原文

我已经设置了一条自定义路线,它似乎有效。但是,我也有同一控制器的资源路由。我想我只是做错了什么,但我无法说出它是什么。老实说,我正在拼凑路线,因为我仍然对如何设置它们以及何时使用什么方法感到有点困惑。

这是我现在正在处理的路线。

resources :shows
match "shows/:country" => "shows#index"

像这样的路线是资源:shows 工作得很好,但不匹配。如果我翻转它们,匹配路线工作正常,但资源:显示不行。

我应该将其作为命名空间路由吗?我不太确定我应该做什么。我想要完成的是这样的事情。

http://site.com/shows/canada

这将返回所有加拿大节目。

任何帮助表示赞赏。

I have setup a custom route, and it seems to work. However, I also have a resources routes as well for the same controller. I think I am just doing something wrong, but I can't tell what it is. I am honestly hacking together routes since I am still a bit confused on how to set them up and when to use what method.

Here are my routes I am dealing with right now.

resources :shows
match "shows/:country" => "shows#index"

The routes like the are the resources :shows works just fine, but not the match. If I flip them the match route works fine, but the resources :shows doesn't.

Should I do this as a namespaced route? I am not exactly sure what I should do. What I am trying to accomplish is something like this.

http://site.com/shows/canada

That will return all Candian shows.

Any help is appreciated.

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

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

发布评论

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

评论(2

白馒头 2024-10-26 18:14:44

您可能想要做的是使用 约束,或者甚至是 自定义约束类。这是一个粗略的开始,我尚未测试过,并且不确定它是否有效:

resources :shows, :constraints => { :id => /[0-9]+/ }
match "shows/:country" => "shows#index", :constraints => { :country => /[a-z]+/ }

请注意,通常这将通过获取查询参数来完成,例如 http://example.com/shows?country=canada,它已经转到您的 shows#index 操作,并将 params[:country] 设置为 “canada”

What you probably want to do is use constraints, or maybe even a custom constraints class. Here's a rough start that I haven't tested and am unsure if it would work:

resources :shows, :constraints => { :id => /[0-9]+/ }
match "shows/:country" => "shows#index", :constraints => { :country => /[a-z]+/ }

Note that typically this would be done via a get query parameter, e.g. http://example.com/shows?country=canada, which would already go to your shows#index action and have params[:country] set to "canada".

滿滿的愛 2024-10-26 18:14:44

您可能会被默认路由所困扰,该路由需要 /{controller}/{action} 并进行相应的路由。尝试删除默认路由。您必须确保声明所有路由,但结果是为您的应用程序提供一组更可预测的路由。

You may be getting bitten by the default route which expects /{controller}/{action} and routes accordingly. Try removing the default route. You will have to make sure to declare all of your routes, but the result is a more predictable set of routes for your app.

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