LoginSignup
4
8

More than 5 years have passed since last update.

Railsのresourcesが親子関係にあるときのroutes.rbの書き方

Last updated at Posted at 2013-02-05

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_」という接頭辞が付与される。

4
8
2

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
4
8