:new、:collection 和 :member 路由之间有什么区别?
I've read the documentation, but I'm still not sure I understand everything.
Especially why there's a :new
parameter. As far as I understand, it could be replaced with the :collection
parameter.
So what's the difference between those three types of routes?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
区别在于生成的 URL。
让我们猜测三个资源:
第一个路由将创建:
控制器名称和操作名称之间没有任何内容。我们不需要任何其他参数来获取用户的列表 rss feed。
第二个将创建操作“配置文件”作为对象的成员。所以我们会得到:
“1”是用户的
to_param
。我们需要用户的 ID 来显示个人资料。第三个将创建行动“草案”作为新行动的成员。因此,我们将:
“草稿”操作在接受其创建之前显示用户的草稿。
这就是 :collection、:member 和 :new 之间的区别。他们每个人都创建了不同的路线,每条路线都有自己的目的。
The difference is the URL generated.
Let's guess three resources :
The first route will create :
With nothing between the controller name and the action name. We don't need any other parameter to get the user's list rss feed.
The second one will create the action "profile" as a member of the object. So we'll have :
The "1" is the user's
to_param
. We need a user's id to display a profile.The third one will create the action "draft" as a member of the new action. So we'll have :
The "draft" action displays a draft of the user before accepting its creation.
So that's the difference between :collection, :member and :new. Every of them creates different routes, each one with their own purpose.
:member
使用模式创建路径/:controller/:id/:your_method
:collection
使用模式/:controller/ 创建路径:your_method
:new
使用模式/:controller/:your_method/new
创建路径(请注意,路径的最后一个元素即new
不变)New
与Collection
的不同主要在于思想层面。这就是 REST 专家如何看待在更大的资源中创建 REST“子资源”。:member
creates path with pattern/:controller/:id/:your_method
:collection
creates path with the pattern/:controller/:your_method
:new
creates path with the pattern/:controller/:your_method/new
(please note that the last element of the path i.e.new
is constant)New
differs fromCollection
mainly on the ideological layer. That's how REST gurus see the creation of the REST "subresource" within the bigger resource.Damiens 的解释大多是正确的,除了关于 :new 的部分之外,
在 http://guides.rubyonrails.org/routing.html 它解释了从内到外的路由,然后再返回。第 3.11.3 节(添加新路由)描述了 :new 的作用,它与 :member 和 :collection 有很大不同。
基本上是map.resources :photos, :new => {:上传=> :post } 将使用 POST HTTP 动词创建 /photos/upload。
Damiens explanation is mostly right except for the section about :new
Have a really good read of the ruby on rails routing guide at http://guides.rubyonrails.org/routing.html It explains routing from the inside out, and then back again. Section 3.11.3 (Adding New Routes) describes what :new does, and it is very different to :member and :collection.
Basically map.resources :photos, :new => { :upload => :post } will create /photos/upload using the POST HTTP verb.