LoginSignup
5
5

More than 5 years have passed since last update.

Railsのルーティング

Last updated at Posted at 2015-12-17

resourcesメソッド (リソースフル)

resources :users
7つ生成される

Prefix Verb URI Pattern Controller#Action 用途 コレクションルート/メンバールート
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 1件表示用 メンバールート
PUT /users/:id(.:format) users#update 編集(更新)処理用 メンバールート
DELETE /users/:id(.:format) users#destroy 削除処理用 メンバールート

resourceメソッド (ノンリソースフル)

resource :page
6つ生成される

Prefix Verb URI Pattern Controller#Action 用途
POST /page(.:format) users#create 新規処理用
new_page GET /page/new(.:format) page#new 新規ページ表示用
edit_page GET /page/edit(.:format) page#edit 編集(更新)ページ表示用
page GET /page(.:format) page#show 1件表示用
PUT /page(.:format) page#update 編集(更新)処理用
DELETE /page(.:format) page#destroy 削除処理用

collectionメソッド 独自のコレクションルートを生やす

resources :users do
  collection do
    get :search
  end
end

memberメソッド 独自のメンバールートを生やす

resources :users do
  member do
    get :profile
  end
end

shallowオプション 子のメンバールートを親を通さずアクセスできるようにする

resources :users, shallow: true do
  resources :comments
end

親子関係に組み込まれるかどうか(今回はcommentsのアクションについて)

Action 親子関係に組み込まれる/組み込まれない
index 組み込まれる
create 組み込まれる
new 組み込まれる
edit 組み込まれない
show 組み込まれない
update 組み込まれない
destroy 組み込まれない

namespaceメソッド スコープとモジュールを変更

個別にscopeメソッドmoduleオプションを指定するのを一気にやってくれる。基本的に個別のscopemoduleは使わず、namespaceを使うことなると思う。
コントローラをディレクトリを作って綺麗に階層構造を作ってる時にURLとディレクトリ構造を合わせたい時に使用。

namespace :admin do
  resources :users
end

参考

5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5