3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Rails基礎】resourcesとresourceの違い

3
Posted at

resources

アプリ上で「複数存在する」リソースを扱う場合に用いる
例:投稿記事、商品、コメント
config/routes.rbにarticlesのリソースを追加する

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

生成されるルーティング

      Prefix Verb   URI Pattern                  Controller#Action
    articles GET    /articles(.:format)          articles#index
             POST   /articles(.:format)          articles#create
 new_article GET    /articles/new(.:format)      articles#new
edit_article GET    /articles/:id/edit(.:format) articles#edit
     article GET    /articles/:id(.:format)      articles#show
             PATCH  /articles/:id(.:format)      articles#update
             PUT    /articles/:id(.:format)      articles#update
             DELETE /articles/:id(.:format)      articles#destroy

resourceと比較した特徴

  • indexがある
  • 「:id」がある
  • 複数件管理

resource

1人のユーザーから見てアプリ上で1つしか存在しないリソースを扱う場合に用いる
例:プロフィール、ユーザー設定、パスワード設定

resource :profileを追加

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

rails route

      Prefix Verb   URI Pattern           Controller#Action
 new_profile GET    /profile/new          profiles#new
     profile GET    /profile              profiles#show
             POST   /profile              profiles#create
edit_profile GET    /profile/edit         profiles#edit
             PATCH  /profile              profiles#update
             PUT    /profile              profiles#update
             DELETE /profile              profiles#destroy

resourcesと比較した特徴

  • indexがない
  • 「:id」がない
  • 1ユーザー1件前提

補足
プロフィールは表示と更新だけのアクションにしたい場合は:onlyオプションを利用します。
resource :profile, only: %i[show edit update]
このように指定すると、指定されたルーティングのみ生成されます。

showの役割は同じ(表示)ですが、
resources では「ID付きの1件表示(詳細ページ)」、
resource では「IDなしの1件表示」になります。

まとめ

RailsではRESTful(HTTPメソッドGET,POST,PATCH,DELETEとURLを組み合わせてアクションと紐づけること)な設計をある程度自動で行なってくれます。
resources と resource は、単数形か複数形かで意味合いが大きく変わります。

つまり、

  • 複数のデータを管理するのか
  • 1ユーザーにつき1件だけ管理するのか

を最初に判断してルーティングを設計することが大切です。

参考文献

パーフェクトRuby on Rails
railsガイド https://railsguides.jp/routing.html

3
1
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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?