嵌套路由的命名参数
resources :leagues do
resources :schedule
end
这会生成:
leagues/:id
leagues/:league_id/schedule/:id
如何防止联盟 ID 更改参数名称? 所以它会是:
leagues/:id
leagues/:id/schedule/:schedule_id
resources :leagues do
resources :schedule
end
This generates:
leagues/:id
leagues/:league_id/schedule/:id
How can I keep the league ID from changing param names?
So it'll be:
leagues/:id
leagues/:id/schedule/:schedule_id
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,请不要这样做。
这样做的原因是它为每个应用程序的嵌套资源提供了一个通用接口。通过在您的应用程序中使其有所不同,您实际上是在“违背 Rails 的原则”。 Rails 有一套严格的约定,您应该遵守。当你偏离这条道路时,事情就会变得混乱。
然而,如果您确实想搬起石头砸自己的脚,打个比方,您将需要手动定义路线。这是控制器中七个标准操作的路由:
正如您所看到的,它非常丑陋。但是,如果您真的真的想这样做,那就这么做。
No, please do not do this.
The reason for it being this way is that it provides a common interface for nested resources across every single application. By making it different in your application, you're effectively going "against the grain" of Rails. Rails has a strict set of conventions that you should stick to. When you stray from this path, things get messy.
However, if you do want to shoot yourself in the foot, metaphorically speaking, you will need to define the routes manually. Here's the routes for the seven standard actions in a controller:
As you can see, it's quite ugly. But, if you really really really want to do it this way, that's how you'd do it.
您可以在资源路由上设置“param”选项来覆盖默认的“id”参数:
参考 Rails 路由文档:http://guides.rubyonrails.org/routing.html#overriding-named-route-parameters
You can set "param" option on resource route to override the default "id" param:
refs to the Rails Routing Doc: http://guides.rubyonrails.org/routing.html#overriding-named-route-parameters
它将 ID 附加到nested_param,这是一个无赖,因为我希望我的没有单一名称。看来他们真的不希望您只将其设置为
:id
因为它可能会发生冲突。另外,这与 Rails 喜欢使用的正常的 Restful 路由有点不同。https://github.com/rails/rails/blob/5368f2508651c92fbae40cd679afbafdd7e98e77/actionpack/lib/action_dispatch/routing/mapper.rb#L1207
Rake 路由返回以下内容
所以接缝更简单的解决方案就是更改控制器以使用它创建的嵌套参数名称。
It appends the ID to the nested_param which is a bummer because I would like mine to be without the singular name. It looks like they really don't want you to make it only like
:id
as it could have conflicts. Plus it would be a bit of a diff from the normal restful routing that rails likes to use.https://github.com/rails/rails/blob/5368f2508651c92fbae40cd679afbafdd7e98e77/actionpack/lib/action_dispatch/routing/mapper.rb#L1207
Rake routes returns the following
So the solution which seams simpler is to just change the controller to use the nested param name it creates.