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?
A member route will require an ID, because it acts on a member. A collection route doesn't because it acts on a collection of objects. Preview is an example of a member route, because it acts on (and displays) a single object.
Member routes can be defined for actions that are performed on a member of the resource . Let's take an example. Let's say we have a post resource and we need an ability to archive a post. To define routes to achive the functionality above, we will use member routes as given below.
Difference between singular resource and resources in Rails routes. So far, we have been using resources to declare a resource. Rails also lets us declare a singular version of it using resource. Rails recommends us to use singular resource when we do not have an identifier.
Decoding the http request TIP: If you ever want to list all the routes of your application you can use rails routes on your terminal and if you want to list routes of a specific resource, you can use rails routes | grep hotel . This will list all the routes of Hotel.
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.
: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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With