memberとcollectionが使われる理由
どちらもresourcesでroutingを設定しているとき、resourcesでは自動で生成されないactionへのroutingを設定するときに使用するもの。
member,collectionルーティングを行うと、新たにルーティングした〇〇_photo_urlヘルパーと〇〇_photo_pathヘルパーも作成される。
memberとcollectionの違いとは
生成するroutingに、:idの有無で決まる。
:idとは 、URL内に記述されるIDのことである。
# rails routes
# id有
/users/:id/follow(.:format)
# id無
/users/slide(.:format)
menberはidが有り、collectionはidが無い。
◆member記入例
この場合はuser resourcesにfollow actionのroutingをmemberで追加したとき、生成されたurlにuserを識別するための:idが自動で追加される。
# member記入例
resources :users do
member do
get :follow
end
end
# 結果
follow_user GET /users/:id/follow(.:format) users#follow
memberルーティングが1つだけしかない場合は、以下のようにルーティングで:onオプションを指定することでブロックを省略できる。
resources :users do
get 'follow', on: :member
end
◆collection記入例
memberと同じように、user resourcesにfollow actionのroutingをcollectionで追加したが、:idは付与されない。
# collection記入例
resources :users do
collection do
get :slide
end
end
# 結果
slide_users GET /users/slide(.:format) users#slide
collectionもmember同様に:onオプションを使える。
resources :users do
get 'slide', on: :collection
end
:onオプションを使ってアクションを追加
また、:onオプションを使って、たとえば以下のように別のnewアクションを追加することもできる。
resources :users do
get 'follow', on: :new
end
上記のようにすることで、GET + /users/new/followのようなパスが認識され、Usersコントローラのfollowアクションにルーティングされる。
まとめ
◆ :id を使用したアクションの場合はmemberを使用する。
◆:idの必要ないアクションの場合は collection を使用する。
参考記事
railsのroutes.rbのmemberとcollectionの違いをわかりやすく解説してみた。〜rails初心者から中級者へ〜
Railsガイド