Rails 自動生成されるパス用メソッド(Named Path)まとめ


リソースのCRUDについては、Rails Guildの2.2 CRUD, Verbs, and Actionsにまとめられています。

よく使うところを抜粋してまとめてみます。

普通のリソース

resource :photos
HTTP Verb Path action Named Helper
GET /photos index photos_path
GET /photos/new new new_photo_path
POST /photos create photos_path
GET /photos/:id show edit_photo_patth(@photo)
GET /photos/:id/edit edit photo_patth(@photo)
PUT /photos/:id update photo_patth(@photo)
DELETE /photos/:id destroy photo_patth(@photo)

resourcesに独自のパスを追加

resources: :posts do
  comment "/comment", on: :collection
end

このときのNamed パスは

comment_posts_path

 

namespeceを使った場合

namespace :admin do
  resources :posts, :comments
end
HTTP Verb Path action named helper
GET /admin/posts index admin_posts_path
GET /admin/posts/new new new_admin_post_path
POST /admin/posts create admin_posts_path
GET /admin/posts/:id show admin_post_path(:id)
GET /admin/posts/:id/edit edit edit_admin_post_path(:id)
PUT /admin/posts/:id update admin_post_path(:id)
DELETE /admin/posts/:id destroy admin_post_path(:id)