読んで欲しい人
-
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でデータは扱えないなと思った。
参考