LoginSignup
0

More than 3 years have passed since last update.

resourcesとresourceの違いについてまとめてみた

Last updated at Posted at 2020-07-29

Railsで何らかのリソースに対するCRUD処理を行うためのルーティングを生成する方法として、resourcesメソッドとresourceメソッドがあるので、今回はその違いについてまとめてみました。

resourcesとは

resourcesメソッドは、コントローラーの7つのアクション(index、show、new、create、edit、update、destroy)をひとまとめにしたメソッドで、複数のリソースに対するCRUD処理を行うためのルーティングを生成します。

config/routes.rb
Rails.application.routes.draw do
 resources :games
end

#リソース名が複数形

上記のように記載すると、7つのアクション(index、show、new、create、edit、update、destroy)全てを設定したことと同じになります。
確認のため、ターミナルにてrails routesコマンドを入力してみると、以下のルーティングが生成されています。

ターミナル
   Prefix Verb   URI Pattern               Controller#Action
    games GET    /games(.:format)          games#index
          POST   /games(.:format)          games#create
 new_game GET    /games/new(.:format)      games#new
edit_game GET    /games/:id/edit(.:format) games#edit
     game GET    /games/:id(.:format)      games#show
          PATCH  /games/:id(.:format)      games#update
          PUT    /games/:id(.:format)      games#update
          DELETE /games/:id(.:format)      games#destroy

リソースが複数なので、/gamesに対するGETリクエストが返すのはリソースの一覧画面(indexアクション)であることが分かると思います。

resourceとは

resourceメソッドは、コントローラの7つのアクション(index、show、new、create、edit、update、destroy)に対して、indexとid付きのパスが生成されません。
resourceは、ただ1つのリソースに対するCRUD処理を行うためのルーティングを生成します。

config/routes.rb
Rails.application.routes.draw do
 resource :game
end

#リソース名が単数形

こちらも確認のため、ターミナルにてrails routesコマンドを入力してみると、以下のルーティングが生成されています。

ターミナル
   Prefix Verb   URI Pattern          Controller#Action
 new_game GET    /game/new(.:format)  games#new
edit_game GET    /game/edit(.:format) games#edit
     game GET    /game(.:format)      games#show
          PATCH  /game(.:format)      games#update
          PUT    /game(.:format)      games#update
          DELETE /game(.:format)      games#destroy
          POST   /game(.:format)      games#create

こちらの場合は、リソースは1つだけなのでurlに:idを含む必要がありません。そして、一覧画面(indexアクション)が必要ないので、/gameに対するGETリクエストはそのリソースの表示(showアクション)であることが分かると思います。

まとめ

「resourcesメソッド」はidが付与されているので、複数あるリソースの中からidを用いて特定のリソースを絞り込むことができます。

その一方で「resourceメソッド」にはidが付与されないので、リソースを絞り込まない状況で使用します。

まとめると、複数存在するリソース(商品やユーザーなど)では「resources」を使用し、1つしか存在しないリソースには「resouece」を使用します。

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
What you can do with signing up
0