resources :books# BooksController:# index => GET /books# new => GET /books/new# create => POST /books/new# show => GET /books/:id# edit => GET /books/:id/edit# update => PUT /books/:id# delete => DELETE /books/:id## Helpers:# new_book_path# book_path(id)# edit_book_path(id)
Member and Collection
collection is for routes on the collection.
member is for routes on a specific member.
Rails.applications.routes.draw do resources :events do collection do post :validate # localhost:3000/events/validateend member do post :publish # localhost:3000/events/1/publishendend
resource :coder# CodersController:# new => GET /coder/new# create => POST /coder/new# show => GET /coder# edit => GET /coder/edit# update => PUT /coder# delete => DELETE /coder
scope 'admin', constraints: { subdomain: 'admin' } do resources ...end
Nested Resources (routes)
Assuming an event has many registrations and we want registration routes to be nested under an event, e.g. localhost:3000/events/1/registrations, we can do:
Rails.applications.routes.draw do resources :events do resources :registrationsendend
First you have to make a new draw method into Rails's routing mapper via an initializer
# config/initializers/routing_draw.rb# Adds draw method into Rails routing# It allows us to keep routing splitted into filesclassActionDispatch::Routing::Mapperdefdraw(routes_name) instance_eval(File.read(Rails.root.join("config/routes/#{routes_name}.rb")))endend
Update your config/routes.rb with the names of files in config/routes/*.rb
# config/routes.rbMyApp::Application.routes.draw do draw :api_v1 draw :api_v2 draw :adminend
New route files
# config/routes/api_v1.rbnamespace :api_v1 do# lots of routesend# config/routes/api_v2.rbnamespace :api_v2 do# lots of routesend# config/routes/admin.rbnamespace :admin do# lots of routesend