resourcesメソッドを指定してRESTfulなルーティングを作る

1.Controllerの作成

$rails g controller books index show new crete edit destroy update

2.ルーティングを作成

vim config/routes.rb
=========================================
  #既に作られているルーティングをコメントアウト(削除)
  #get 'books/index'
  #get 'books/show'
  #get 'books/new'
  #get 'books/crete'
  #get 'books/edit'
  #get 'books/destroy'
  #get 'books/update'

  #resoucesを設定(index/show/new/create/edit/destroy/update全部)
  resources :books

  #resoucesを設定(show/newだけに限定したい場合)
  #resources :books, only: [:show, :new]
=========================================

3.ルーティングを確認

$rake routes
Prefix Verb   URI Pattern                Controller#Action
         books GET    /books(.:format)           books#index
               POST   /books(.:format)           books#create
      new_book GET    /books/new(.:format)       books#new
     edit_book GET    /books/:id/edit(.:format)  books#edit
          book GET    /books/:id(.:format)       books#show
               PATCH  /books/:id(.:format)       books#update
               PUT    /books/:id(.:format)       books#update
               DELETE /books/:id(.:format)       books#destroy

4.ブラウザからアクセスして確認する

http://localhost/books => Books#index
http://localhost/books/new => Books#new
http://localhost/books/1/edit => Books#edit
http://localhost/books/1 => Books#show

5その他

5-1.member,collectionを使って、アクションを追加する

memberかcollectionを用いると、index/show/new/create/edit/destroy/update以外の
アクションを追加することができる。
memberは:idがあるルートで、collectionは:idなしのルートの指定に用いられる

vim config/routes.rb
=========================================
  #resoucesを設定(index/show/new/create/edit/destroy/update全部)
  #resources :books

  resources :books do
    member do
      get 'preview'
    end

    collection do
      get 'search'
    end
  end
=========================================

ルーティングをかくにんする
previewとsearchのルーティングが追加されている。

$rake routes
Prefix Verb   URI Pattern                Controller#Action
	preview_book GET    /books/:id/preview(.:format) books#preview
	search_books GET    /books/search(.:format)      books#search

5-2.Controller名を変更する

[before]http://localhost/books --> [after]http://localhost/memos

vim config/routes.rb
=========================================
resources :users, :controller => 'members'
=========================================
$rake routes
=========================================
 memos GET    /memos(.:format)           books#index
               POST   /memos(.:format)           books#create
      new_memo GET    /memos/new(.:format)       books#new
     edit_memo GET    /memos/:id/edit(.:format)  books#edit
          memo GET    /memos/:id(.:format)       books#show
               PATCH  /memos/:id(.:format)       books#update
               PUT    /memos/:id(.:format)       books#update
               DELETE /memos/:id(.:format)       books#destroy
=========================================