RESTful嵌套带有单个标识符的资源路由 [英] RESTfully Nesting Resource Routes with Single Identifiers
问题描述
在我的Rails应用程序中,两个实体之间具有相当标准的has_many关系. Foo
具有零个或多个Bars
;一个Bar
恰好属于一个Foo
. Foo和Bar均由单个整数ID值标识.这些值在所有其各自的实例中都是唯一的.
In my Rails app I have a fairly standard has_many relationship between two entities. A Foo
has zero or more Bars
; a Bar
belongs to exactly one Foo
. Both Foo and Bar are identified by a single integer ID value. These values are unique across all of their respective instances.
酒吧的存在取决于Foo:没有Foo的酒吧是没有道理的.
Bar is existence dependent on Foo: it makes no sense to have a Bar without a Foo.
有两种方法可以RESTful地引用这些类的实例.假设Foo.id为"100",Bar.id为"200":
There's two ways to RESTfully references instances of these classes. Given a Foo.id of "100" and a Bar.id of "200":
-
通过各自的顶级" URL路由引用每个Foo和Bar,如下所示:
Reference each Foo and Bar through their own "top-level" URL routes, like so:
- /foo/100
- /bar/200
参考栏通过其Foo实例作为嵌套资源:
Reference Bar as a nested resource through its instance of Foo:
- /foo/100
- /foo/100/bar/200
我喜欢#2中的嵌套路由,因为它更紧密地表示了实体之间的实际依赖关系.但是,它似乎确实涉及很多额外的工作,却收效甚微.假设我了解某个特定的酒吧,则无需告诉我特定的Foo.我可以从律师协会本身得到这一点.实际上,我可能应该在任何地方验证路由的Foo(以便假设Bar 200未分配给Foo 150,所以您不能执行/foo/150/bar/200).最终,我看不出这给我带来了什么.
I like the nested routes in #2 as it more closely represents the actual dependency relationship between the entities. However, it does seem to involve a lot of extra work for very little gain. Assuming that I know about a particular Bar, I don't need to be told about a particular Foo; I can derive that from the Bar itself. In fact, I probably should be validating the routed Foo everywhere I go (so that you couldn't do /foo/150/bar/200, assuming Bar 200 is not assigned to Foo 150). Ultimately, I don't see what this brings me.
那么,对于这两种路由方案,是否有任何 other 自变量?
So, are there any other arguments for or against these two routing schemes?
我最关心的是对特定Bar的RESTful更新/显示/删除.为了获得特定Foo的Bar列表(在Rails中通常是索引"动作),具有嵌套路由(例如/foo/100/bar)是很有意义的.不过,使用此路由的页面可以像/foo/100/bar/x一样轻松地链接到/bar/x.
I'm concerned mostly about RESTful updates/shows/deletes to particular Bars. For getting a list of Bars for a specific Foo (which is usually the "index" action in Rails) it makes perfect sense to have a nested route such as /foo/100/bar. The page at this route could just as easily link to /bar/x as /foo/100/bar/x though.
推荐答案
您正在寻找浅层路线.正如您所指出的那样,无需为诸如创建,更新之类的应用建立深层嵌套的路由,因为您可以直接定位所需的记录.
You're looking for shallow routes. As you pointed out, the idea of having a deeply nested route for things like creates, updates is unnecessary since you are targeting the desired record directly.
我实际上从未做过浅层布线工作,因此我将继续讲讲Railscast情节,在该情节中Ryan Bates可能比我更能说明这一点:
I have never actually done the shallow routing thing so I'll pass on the railscast episode where Ryan Bates explains it probably better than I could: 139 Nested Resources.
您可以在路由指南3.8.4中阅读更多内容. .
这篇关于RESTful嵌套带有单个标识符的资源路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!