LoginSignup
1
1

More than 3 years have passed since last update.

Railsのmemberとcollectionについて

Posted at

ルーティングにはindex,new,create,destroy,edit,update,showの7つのアクションがありますが、他にもcollectionとmemberというのがあります。
collectionはルーティングに:idが付かず、memberは:idがつくという違いがあります。

collectionの場合

Rails.application.routes.draw do
  resources :tweets do
    collection do
      get 'search'
    end
  end
end
Prefix           Verb    URI                                 Pattern
search_tweets    GET    /tweets/search(.:format)              tweets#search

idがついていません。
menberの場合

Rails.application.routes.draw do
  resources :tweets do
    member do
      get 'search'
    end
  end
end
Prefix           Verb    URI                                 Pattern
search_tweet      GET    /tweets/:id/search(.:format)       tweets#search

idがついています。

データ全体にアクションを起こす時はcollection、特定のデータにアクションを起こす時はmemberという風につか分けるのかなと。
検索機能を実装したい時はデータ全体へのアクションが必要なのでmemberを使うということになります。

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