はじめに
ルーティングのメソッドについてふわっとした理解のままでいたので、改めて今まで使ってきたもの、プラスそのメソッド周りのオプションをまとめてみた。
・resources
・only(オプション)
・except(オプション)
・collection
・member
・on(オプション)
・namespace
・scope
・as(オプション)
・controller
resources
CRUD機能のルートを一式定義できる
resources :blogs
:only
onlyオプションは特定のルーティングを作成
resources :blogs, only: [:index]
:except
exceptオプションはonlyの反対で指定したアクションは作成しない
resources :blogs, except: [:edit, update]
resourcesにブロックを渡す
collection, member
collection
idを必要としないルーティングの生成/blogs/confirm
resources :blogs do
collection do
get 'confirm'
end
end
member
idを必要とするルーティングの生成/blogs/1/preview
resources :blogs do
member do
get 'preview'
end
end
on
onオプションはcollection, memberのブロック内にルーティングが1つしかない場合は省略して書くことができる。
resources :blogs do
get 'confirm', on: :collection
end
resources :blogs do
get 'preview', on: :member
end
namespaceとscope
namespace
多数のコントローラ群をまとめることができる
ファイル構成も指定される
これによりURL、名前付きルーティングヘルパー(パス)などが生成される
namespace :admin do
resources :users
end
例
Helper HTTP URI Pattern Controller#Action
admin_users GET /admin/users(.:format) admin/users#index
scope
URLのパスの指定のみ
ファイル構成、ルーティングヘルパーは変わらない
scope :blogs do
resources :articles
end
例
Helper HTTP URI Pattern Controller#Action
articles GET /blog/articles(.:format) articles#index
as
scopeにasオプションを使用すると、ルーティングヘルパーに名前をつけることができる
(他にも:modle, :pathを指定できる)
scope :blogs do
resources :articles, as: 'hoge_articles'
end
例 ヘルパーのみ変更されてる
Helper HTTP URI Pattern Controller#Action
hoge_articles GET /blogs/articles(.:format) articles#index
namespaceスコープは:moduleや:pathプレフィックスに加えて:asも自動的に追加される。
controller
コントローラーを指定してコードをまとめることができる。
構造と結びつけて記述することで可読性があがる
controller :blogs do
scope :blogs do
resources :articles, as: 'hoge_articles'
end
end
ネストしたルーティング
親子関係をルーティングで表現できる
親に加えて、ネストされた子のルーティングも生成される
resources :admins do
resources :users
end
(namespaceと何が違うの??ということで上記のnamespaceと同じコントローラー名で比較してみた。)
URL: /admins/:admin_id/users(.:format)
親のidが追加されていた、以上
Helper HTTP URI Pattern Controller#Action
admins_users GET /admins/:admin_id/users(.:format) users#index
※ネストは1回にとどめること、2回以上はルーティングが扱いにくくなる。