Resource Routing Basic

suggest change

Routes are defined in config/routes.rb. They are often defined as a group of related routes, using the resources or resource methods.

resources :users creates the following seven routes, all mapping to actions of UsersController:

get       '/users',          to: 'users#index'
post      '/users',          to: 'users#create'
get       '/users/new',      to: 'users#new'
get       '/users/:id/edit', to: 'users#edit'
get       '/users/:id',      to: 'users#show'
patch/put '/users/:id',      to: 'users#update'
delete    '/users/:id',      to: 'users#destroy'

Action names are shown after the # in the to parameter above. Methods with those same names must be defined in app/controllers/users_controller.rb as follows:

class UsersController < ApplicationController
  def index
  end

  def create
  end

  # continue with all the other methods…
end

Limit the generated actions with only or except. These two lines are alternatives. Declaring both in one file defines resources :users twice:

resources :users, only: [:show]
resources :users, except: [:show, :index]

List every route with rails routes (rake routes on Rails 4):

users     GET    /users(.:format)          users#index
          POST   /users(.:format)          users#create
new_user  GET    /users/new(.:format)      users#new
edit_user GET    /users/:id/edit(.:format) users#edit
user      GET    /users/:id(.:format)      users#show
          PATCH  /users/:id(.:format)      users#update
          PUT    /users/:id(.:format)      users#update
          DELETE /users/:id(.:format)      users#destroy

To see only the routes that map to a particular controller:

rails routes -c static_pages
static_pages_home    GET    /static_pages/home(.:format)    static_pages#home
static_pages_help    GET    /static_pages/help(.:format)    static_pages#help

You can search through routes using the -g option. This shows any route that partially matches the helper method name, the URL path or the HTTP verb:

rails routes -g new_user    # matches a helper name
rails routes -g POST        # matches the POST verb

In development, /rails/info/routes lists the same routes, first match at the top. One row looks like users_path, GET, /users(.:format), users#index.

resource (singular) declares one record and omits :id from the path. It is not the same as a member route. index is left out unless you ask for it:

resource :orders, only: [:index, :create, :show]

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents