Railsで簡単なブログアプリケーションを作っていたとする。
posts
で記事のリソースを作り、posts
に紐づくようにcomments
のリソースが親子関係にあるとき。
routes.rbの書き方
resources :posts do
resources :comments
end
rake routesで確認
post_comments GET /posts/:post_id/comments(.:format) comments#index
POST /posts/:post_id/comments(.:format) comments#create
new_post_comment GET /posts/:post_id/comments/new(.:format) comments#new
edit_post_comment GET /posts/:post_id/comments/:id/edit(.:format) comments#edit
post_comment GET /posts/:post_id/comments/:id(.:format) comments#show
PUT /posts/:post_id/comments/:id(.:format) comments#update
DELETE /posts/:post_id/comments/:id(.:format) comments#destroy
(...後略...)
ネストされたリソースではURLパターンは「/posts/:post_id」、Urlヘルパーには「post_」という接頭辞が付与される。