0
0

More than 1 year has passed since last update.

【Rails】memberとcollectionの違い

Posted at

membercollectionが使われる理由

どちらもresourcesでroutingを設定しているとき、resourcesでは自動で生成されないactionへのroutingを設定するときに使用するもの。

member,collectionルーティングを行うと、新たにルーティングした〇〇_photo_urlヘルパー〇〇_photo_pathヘルパーも作成される。

membercollectionの違いとは

生成するroutingに、:idの有無で決まる。

:idとは 、URL内に記述されるIDのことである。

#rails routes

#id有
/users/:id/follow(.:format)  

#id無
/users/slide(.:format)

menberはidが有り、collectionはidが無い。

◆member記入例
この場合はuser resourcesfollow 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 resourcesfollow 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ガイド

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