LoginSignup
135
108

More than 3 years have passed since last update.

railsのroutes.rbのmemberとcollectionの違いは?

Posted at

はじめに

Railsでroutes.rbを設定するとき、membercollectionを記述することがあります。

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

resource :user_sign_ups do
  collection do
    get :tell 
  end
end

このmemberやcollectionはどんな役割をしているのでしょうか?

memberとcollectionの違いは?

簡単に言うと、routingにidが付くか付かないかの違いです。

もう少しわかりやすく説明するために例をだして解説します。

resources :users  do
  member do
    get :logout
  end
end

users#logoutをmemberでルーティングを設定すると、URLは以下のようになります。

/users/:id/logout

このようにuserを識別するための:idが追加されます。

では、collectionでルーティングを設定した場合はどうなるでしょう?

resource :user_sign_ups do
  collection do
    get :tell 
  end
end

user_sign_ups#tellをcollectionでルーティングを設定しました。

すると

/user_sign_ups/tell

urlに:idが追加されていません。

:idでurlを識別する必要がない場合はcollectionで設定します。

おわりに

まとめると

memberは特定のデータにアクションを利用する
collectionは全体のデータにアクションを利用する

ときに設定します・

135
108
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
135
108