0
0

[Rails] routes.rbのresource, resourcesの違い

Posted at

目的

現在携わっているRails のプロジェクトのroutes.rbで、名前が似ているresourceメソッド,resourcesメソッドが使用されていたので、その意味、違いについてまとめる。

resources

7つのアクション(index、show、new、create、edit、update、destroy)のルーティングを一括生成してくれるメソッド
例)
routes.rbに

routes.rb
Rails.application.routes.draw do
  resources :users
end

と書くと,

$ rails routes
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
		  PATCH  /users/:id(.:format)         users#update
		  PUT    /users/:id(.:format)         users#update
		  DELETE /users/:id(.:format)         users#destroy

のルーティングが生成

resource

6つのアクション(show、new、create、edit、update、destroy)のルーティングを一括生成してくれるメソッド
例)
routes.rbに

routes.rb
Rails.application.routes.draw do
  resource :user
end

と書くと

$ rails routes
new_user  GET    /user/new(.:format)           users#new
edit_user GET    /user/edit(.:format)          users#edit
user      GET    /user(.:format)               users#show
		  PATCH  /user(.:format)               users#update
		  PUT    /user(.:format)               users#update
		  DELETE /user(.:format)               users#destroy
		  POST   /user(.:format)               users#create

resourcesとresourceの違い

  • resourcesにはindexアクションのルーティングがあり、resourceにはない
  • resourcesには7つのアクションのルーティングがid付きで生成されるが、resourceはidなしで生成される。
    つまり、resourceメソッドは複数あるリソースをひとつに絞れない。

resourcesとresourceの使い分け

  • resourcesはusers, postsなど複数存在するリソースに使用。
  • resourceはuserのprofileなどログインユーザーから見て一つしか存在しないリソースに使用。

ちなみにRails APIモードだと...

routes.rbにresources :usersと書くと...

$ rails routes
users GET    /users(.:format)        users#index
      POST   /users(.:format)        users#create
 user GET    /users/:id(.:format)    users#show
      PATCH  /users/:id(.:format)    users#update
      PUT    /users/:id(.:format)    users#update
      DELETE /users/:id(.:format)    users#destroy

のルーティングが生成。

routes.rbにresource :userと書くと...

$ rails routes
user GET    /user(.:format)    users#show
	 PATCH  /user(.:format)    users#update
	 PUT    /user(.:format)    users#update
	 DELETE /user(.:format)    users#destroy
	 POST   /user(.:format)    users#create

新規登録画面表示のnewアクション、編集画面表示のeditアクションがなくなった。

参考にさせていただいた記事

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