Railsのルーティング
1つのルートの定義
get '/login', to: 'sessions#new'
ここでは次のことを定義している。
GETメソッドで'/login'というURLにリクエストが来たら、SessionsControllerのnewアクションを呼び出す。また、このURLをlogin_pathというヘルパーメソッドで生成できるようになる。
この結果、「link_to」メソッドでもURLヘルパーメソッドを使えるようになる。以下はその例。「/login」「/tasks/new」のようなパスを取得することが可能になる。
link_to 'ログイン', login_path, class: 'btn-primary' link_to '新規登録', new_task_path, class: 'btn-primary'
RESTfulなルート
resources :users
この1行だけで、RESTfulなUsersリソースで必要となるすべてのアクションが利用できるようになる。わざわざ「get '/users', to: ''users#index」などと書かなくてもいい。ただし、RESTful以外の「/login」「/concept」などではその都度、ルーティングを定義する必要がある。
RESTfulなUsersリソースで必要となるすべてのアクションは以下の7通り。これは「resources」を書くだけですべて定義される。
HTTPリクエスト | URL | アクション | 名前付きルート | 用途 |
---|---|---|---|---|
GET | /users | index | users_path | 全ユーザーの一覧 |
GET | /users/1 | show | user_path(user) | 各ユーザーのページ |
GET | /users/new | new | new_user_path | ユーザーの新規登録ページ |
POST | /users/ | create | users_path | ユーザーの新規登録を行う |
GET | /users/1 | edit | edit_user_path(user) | id=1のユーザーを編集するページ |
PATCH | /users/1 | update | user_path(user) | id=1のユーザーを更新する |
DELETE | /users/1 | destroy | user_path(user) | id=1のユーザーを削除する |
一部のルートの除外
resoucesを用いつつ、7つのルートの中から使うルートを限定することもできる。
# indexのルートのみ定義 resources :tasks, only: [:index] # delete, edit, update以外のルートのみ定義 resources :tasks, except: [:delete, :edit, :update]
ルートの構造化
ルートが増えると、可読性も落ちてくる。そこでnamespaceなどを用いてルートを構造化する必要がある。
namespace :admin do resources :users, only: [index] get "/test/read",:to=>"test#read" end # 使えるパス GET /admin/users admin/users#index GET /admin/test/read(.:format) admin/test#read