プログラミングのメモ帳

自分のメモとして残したいアウトプット

Railsルーティングのあれこれ(routes.rb)

Railsのルーティングの指定方法に色々種類があったので 自分用に整理する

基本形

get '/login', to: 'sessions#new'

httpメソッド 'パス', to: 'コントローラー#アクション'
という書き方。

CRUD機能を一括で指定

resources :users

resources :コントローラー名
CRUDの各機能を満たすルーティングが一括で指定される。

上記の例でいうと

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

の7つのルーティングが一括で指定される。 基本的な機能は一発でルーティングされるがURLパターンを変更したい場合(login等)は個別に指定するべし

resourceから特定の機能のみルーティング

resourcesメソッドの第二引数に'only: []'をつけることで特定のアクションのみ実装する

#indexとshowアクションのみにルーティング
resources :users, only: [:index, :show]

namespace(名前空間)を指定する

Controllerに名前空間が指定されている場合、routes.rbにもnamespaceを指定する。

#admin/posts_controllerを指定する場合
namespace :admin do
  get '/users', to: 'users#index
end

上記のroutesは

'admin/users', to: 'admin/users#index

と同じになる。

scopeを使って柔軟に指定する

URLパターンだけ一括で変更したい、逆にコントローラーだけ一括で指定したい。
という場合にはscopeを使う。

scope :admin do
  get '/users', to: 'users#index 
end

これは

  get 'admin/users', to: 'users#index'

を同じになる。(URLパターンだけ名前空間が付与される)

scope module: 'admin' do
  get '/users', to: 'users#index 
end

  get 'users', to: 'admin/users#index'

と同じ。(コントローラーにだけ名前空間が付与される。)