LoginSignup
2
3

More than 3 years have passed since last update.

【Rails】collectionとmemberの違い

Posted at

はじめに

学習中の備忘録です。

概要

7つの基本アクション以外でルーティングを定義する時の、collectionとmemberの違い。
結論:collectionはルーティングに:idがつかない、memberは:idがつく。

前提

  • rails 5.2.3
  • postsテーブルを検索するsearchアクションを定義
  • 今回はcollectionとmemberの違いのみ。searchメソッドは定義済とする。

collectionで定義した場合

Rails.application.routes.draw do
  resources :posts do
    collection do
      get 'search'
    end
  end
end

collectionのルーティング

Prefix          Verb    URI                                 Pattern
search_posts    GET     /posts/search(.:format)             posts#search

memberで定義した場合

Rails.application.routes.draw do
  resources :posts do
    member do
      get 'search'
    end
  end
end

memberのルーティング

Prefix           Verb    URI                               Pattern
search_post      GET    /posts/:id/search(.:format)        posts#search

まとめ

URIの指定先が、collectionが:idなし、memberが:idありとなっていることが確認できます。

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