What's the difference between :new, :collection and :member routes?
-
13-09-2019 - |
Question
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?
Solution
The difference is the URL generated.
Let's guess three resources :
map.resources :users, :collection => { :rss => :get }
map.resources :users, :member => { :profile => :get }
map.resources :users, :new => { :draft => :get }
The first route will create :
/users/rss
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 :
/users/1/profile
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 :
/users/new/draft
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.
OTHER TIPS
: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 from Collection
mainly on the ideological layer. That's how REST gurus see the creation of the REST "subresource" within the bigger resource.
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.