LoginSignup
153

More than 5 years have passed since last update.

railsのroutes.rbのmemberとcollectionの違いをわかりやすく解説してみた。〜rails初心者から中級者へ〜

Last updated at Posted at 2019-02-17

この記事の対象者

rails tutorialも終わり、resourcesはわかるけどmemberとかcollectionは知らない人。

内容

routes.rbで使用される、memberとcollectionの違いを解説します。

memberとcollectionが使用される目的

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

resources :users do
    member do
      get :follow
        #follow_user GET    /users/:id/follow(.:format)            users#follow
      get :like
        #like_user GET    /users/:id/like(.:format)                users#like
    end
end

user resourcesをroutingに設定しているとき、users controllerのfollow actionをroutingに設定したいって思ったとき、こんな感じで使用します。

memberとcollectionの違い

生成するroutingに、:idが付くか付かないか。

memberは付いてcollectionは付かないです。

memberの特徴

:idが付く。以上。

そんな事言ったら怒られそうなので詳しく書きます。

resources :users do
    member do
      get :follow
    end
end
follow_user GET    /users/:id/follow(.:format)                    users#follow

こんな感じでuser resourcesにfollow actionのroutingをmemberで追加したとき、生成されたurlにuserを識別するための:idが自動で追加されます。

collection

memberの時と同様に、user resourcesにslide actionへのroutingを追加します。

resources :users do
    collection do
      get :slide
    end
end
slide_users GET    /users/slide(.:format)                        users#slide

こんな感じで追加されるslide actionのurlにはuserを識別するための:idがつきません。

最後に

最後までお読みくださりありがとうございました。なんか間違いあれば指摘ください。

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
153