resources
resources
で7つアクション(index・show・new・create・edit・update・destroy)
に7つのルートを自動で設定できる。
resources : リソース名 [,オプション]
config/routes.rb
resources :users
アクション | HTTPメソッド | URLパターン |
---|---|---|
index | GET | /users |
show | GET | /users/:id |
new | GET | /users/new |
create | POST | /users |
edit | GET | /users/:id/edit |
update | PATCHまたはPUT | /users/:id |
destroy | DELETE | /users/:id |
ヘルパーメソッド | URLパターン名 | 機能 |
---|---|---|
users_path | users | 一覧画面 |
user_path | user | 詳細画面 |
new_user_path | new_user | 新規登録画面 |
users_path | users | 登録処理 |
edit_user_path | edit_user | 編集画面 |
user_path | user | 更新処理 |
user_path | user | 削除処理 |
only
:only
オプションは、特定アクションのルートだけを作成する。
たとえば、only:[:index]とすると、indexのルートだけが作成される。
config/routes.rb
resources :users, only:[:index]
excep
:excep
オプションは、特定アクションのルートだけを作成する。
except:[:index, :show]とすると、indexとshow以外の5つのルートが作成される。
config/routes.rb
resources :users, except:[:index, :show]
collection
ユーザー検索をおこなう、searchアクションを新規追加するなど、
全データに対するアクションに利用する場合は、resourcesにcollection
ブロックをわたす。
config/routes.rb
resources :users do
collection do
get 'search'
end
end
# onオプションを使った場合
resources : users do
get 'search', on: :collection
end
member
特定のユーザーを示す id 付きのルーティングのように、特定のデータに対するアクションに利用する場合は、resourcesにmember
ブロックをわたす。
config/routes.rb
resources :users do
member do
get 'preview'
end
end
# onオプションを使った場合
resources : users do
get 'preview', on: :member
end