ルーティングのあれこれ
scope
,namespace
,member
,collection
,resources
,resource
ルーティングを書く際にゴリゴリに一つずつパスを書いていかずに、これらを使っていきたい。
しかし、いまいちどう使っていいのか分からなかったので、自分なりに例をあげて、目的のルーティングを作成してみた。
目標とするパス
GET user/publishers/{publisher_id}/books # 本一覧
GET user/publishers/{publisher_id}/books/{book_id}/comments # コメント一覧
POST user/publishers/{publisher_id}/books/{book_id}/comments # コメント投稿
DELETE user/publishers/{publisher_id}/books/{book_id}/comments/id # コメント削除
ある出版社の本に対するコメントを見たり、投稿したりするケースについて考える。
scopeとnamespaceの違い
namespace
は、URLもcontroller格納フォルダも、指定のパスになる。
scope
はURLのみ、指定のパスになる。
参照
routeのmoduleとnamespaceとscopeの違い
resources,resourceの違い
resources
がHTTPメソッドのGET、POST、PUT(PATCH)、DELETEでidをとるもの。
resource
がidを取らないもの。
参照
Railsのresourcesとresourceついて
ここまでで、一旦下記を作成。
GET user/publishers/{publisher_id}/books
books_id
を取ることを考えて、resources
を用いる。
namespace 'user' do
resources :publishers, only: [:index]
resources :books, only: [:index]
end
end
books GET user/publishers/:publisher_id/books(.:format) books#index
member,collectionの違い
resourcesでroutingを設定しているとき、resourcesでは自動で生成されないactionへのroutingを設定するときに使用する。
memberとcollectionの違いは、生成するroutingに、:idが付くか付かないか。
memberは付いてcollectionは付かない。
参照
railsのroutes.rbのmemberとcollectionの違いをわかりやすく解説してみた。〜rails初心者から中級者へ〜
これをもとに
GET user/publishers/{publisher_id}/books/{book_id}/comments # コメント一覧
POST user/publishers/{publisher_id}/books/{book_id}/comment # コメント投稿
DELETE user/publishers/{publisher_id}/books/{book_id}/comment # コメント削除
これらを作成する。books_idを必要とするので、使用するのはmember
namespace 'user' do
resources :publishers, only:[:index] do
resources :books, only: [:index] do
member do
resources :comments, only: [:index, :destroy, :create]
end
end
end
end
comments GET user/publishers/:publisher_id/books/:id/comments(.:format) user/comments#index
comment_book DELETE user/publishers/:publisher_id/books/:id/comment(.:format) user/comment#destroy
POST user/publishers/:publisher_id/books/:id/comment(.:format) user/comment#create
books GET user/publishers/:publisher_id/books(.:format) user/books#index
目標どおりのパス作成完了。
きれいに書けた。
追記
member
を使用せずともresourses
のネストでかけるとのご指摘を頂いたので、修正します。
namespace 'user' do
resources :publishers, only:[:index] do
resources :books, only: [:index] do
resources :comments, only: [:index, :destroy, :create]
end
end
end
こちらでも同様のルートがとれますね。