What is the difference between new, collection, and member in Rails Routes? railsroutes
By default, there are seven RESTful routing verbs (index, show, create, new, edit, update, and destroy ). Sometimes we need to customize the route, then we need to use the: on parameter. : The on parameter has three values: collection, member, and new.
If you want to add a member route, you can:
Copy codeThe Code is as follows:
Resources: photos do
Member do
Get 'preview'
End
End
A route will be added: GET request/photos/1/preview route to the preview action of PhotosController, And the preview_photo_url and preview_photo_path helpers will also be created.
You can add many records to the above member block. If there is only one entry, it is generally written as follows:
Copy codeThe Code is as follows:
Resources: photos do
Get 'preview', n =>: member
End
The following summarizes the differences between member, new, and collection:
: Member is used to operate a single object. The route creation format is:/: controller/: id/: your_method.
: Collection is an operation on the object set. The route format for creating a collection is:/: controller/: your_method.
: New is to create a new object. The route creation format is:/: controller/: your_method/new.
Example:
Copy codeThe Code is as follows:
Map. resources: users,: collection =>{: rss =>: get}
Map. resources: users,: member =>{: profile =>: get}
Map. resources: users,: new =>{: draft =>: get}
The route created in the first line is:/users/rss
The route created in the second line is:/users/1/profile
"1" is user_id. We need to know the user ID to get the user's profile.
The route created in the third line is/users/new/draft.