LoginSignup
0
0

More than 1 year has passed since last update.

Rails memberとcollectionの違い

Posted at

結論

memberを用いることでidを用いて特定のリソースに対してアクションを実行することができ、collectionを用いることで全てのリソースに対してアクションを実行することができる。

公式API

member
https://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/Resources.html#method-i-member
collection
https://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/Resources.html#method-i-collection

member

routes.rb
resources :users do
    member do
        get :hoge
    end
end

memberを使うとルーティングは以下のようになります。
スクリーンショット 2022-01-10 15.28.02.png

idを指定することができるので特定のUserに対してhogeアクションを行いたい場合に用いることができます。

collection

routes.rb
resources :users do
    collection do
        get :piyo
    end
end

collectionを用いるとルーティングは以下のようになります。
スクリーンショット 2022-01-10 15.29.34.png

memberを用いた場合とは異なり、idを指定しないので全てのUserに対してpiyoアクションを行いたい場合に用いることができます。

おわりに

特定のリソースに対してアクションを実行するか、全てのリソースに対してアクションを実行するかによってmemberとcollectionを使い分けることが必要です。

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