1
0

ネストしたルーティングの_pathヘルパーについて

Last updated at Posted at 2024-07-02

読んで欲しい人

  • link_to post_edit_path(@post, @hoge)でなんで2つ引数を入れているかわからん人へ
  • 過去の自分

動作環境

  • ruby 3.3.0
  • Rails 7.1.3.3

pathヘルパーとは

  • URLを生成するための便利なヘルパー

こんなルーティングがあったら

routes.rb
resources :posts

下記のようにURLを生成してくれる

  • posts_path→/posts
  • new_post_path→/posts/new
  • edit_post_path(:id)→/posts/:id/edit
  • post_path(:id)→/posts/:id

今回メインに扱うのは下記

  • edit_post_path(:id)→/posts/:id/edit
  • post_path(:id)→/posts/:id

基本的に、ビューやコントローラにedit_post_path(@posts)という使い方をする。
引数を指定して、リンクを生成してくれる。

リソースがネストしている時のlink_to

下記の場合:ポストに紐づいたコメントがあるとき

resources :posts do
  resources :comments
end

生成されるURL

post_comments GET    /posts/:post_id/comments(.:format)   comments#index
              POST   /posts/:post_id/comments(.:format)   comments#creat
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
            PATCH  /posts/:post_id/comments/:id(.:format)  comments#update
            PUT    /posts/:post_id/comments/:id(.:format)   comments#update
            DELETE /posts/:post_id/comments/:id(.:format)  comments#destroy

その時に

  • edit_post_comment_path(@comments)
  • post_comment_path(@comments)

のように指定すると、うまくURLが生成されない。

  • edit_post_comment_path(@post, @comments)

とか

  • post_comment_path(@comments.post, @comments)

みたいに、2つの引数を指定する必要がある。

投稿に紐づいたコメントなので、post_idに紐づいたcomment_idを指定してあげないと、URLが正確に生成されない。

post_comment GET    /posts/:post_id/comments/:id(.:format)

引数の順番はルーティングを確認する。

最初に:post_id次に:id(comment_id)を引数に指定する

学び・感想

  • ネストしたルーティングが苦手すぎる
  • とりあえず、メモとして残せてよかった
  • リソースの構造を知らないとRailsでデータは扱えないなと思った。

参考

1
0
1

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
1
0