LoginSignup
0
0

【Rails】resourcesとは

Last updated at Posted at 2022-08-16

はじめに

この記事は、resourcesに関する基礎知識をまとめた記事である。(備忘録的な意味もあります…)
 ・前提
 ・resourcesとは
 ・書き方
 ・注意事項

前提

・Railsのルーティングを理解している

resourcesとは

resourcesとは、特定のコントローラーに対するルーティングをまとめて設定してくれるもの。

設定するルーティングは、データベース上でのCRUD操作(Create/Read/Update/Delete)にそれぞれ対応できるようなルーティングを設定してくれる。

index、new、create、show、edit、update、destroyアクションに対するルーティングを設定してくれる。

書き方

基本

・書く場所:config/routes.rb
・書き方 :resources :コントローラー名

config/routes.rb
resources :コントローラー名

 
例:postsコントローラーのルーティングを設定する場合

config/routes.rb
resources :posts

作成されるルーティングの一覧

HTTP verb パス Controller#Action
GET /posts posts#index
GET /posts/new posts#new
POST /posts posts#create
GET /posts/:id posts#show
GET /posts/:id/edit posts#edit
PATCH/PUT /posts/:id posts#update
DELETE /posts/:id posts#destroy

複数書く方法

複数のコントローラーに対してresourcesを書く方法は複数ある

①それぞれのコントローラー分書く

例:posts、commentコントローラーのルーティングを設定する場合

config/routes.rb
resources :posts
resources :comments

②1行でまとめて書く(略記法)

例:posts、commentコントローラーのルーティングを設定する場合

config/routes.rb
resources :posts, :comments

 
ただし、②は①と完全に同一の意味を持つ

注意事項

ルーティングが読み込まれる順番(ファイルの上から下に読み込まれる)を考慮して記述する必要がある

まとめ

・resourcesとは
index、new、create、show、edit、update、destroyアクションに対するルーティングを設定してくれる。

0
0
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
0
0