前提条件
- Ruby 3.1.0
- Rails 7.0.4
エラー事象
ルーティングのネストは正しく記述されているはずなのに、Prefixnew_user_food_path
が利用できない。ActionController::UrlGenerationErrorが発生する。
config/route.rb
resources :users do
resources :microposts
end
user/show.html.erb
<div class="top-wrapper">
<%= link_to "新規投稿", new_user_micropost_path %>
</div>
原因
new_user_micropost_pathの引数にユーザ情報がなかった
$ rails routes
でルーティングをよく見ると、
new_user_micoropost
のURI Patternは/users/:user_id/~
、
user
のURI Patternは/users/:_id/~
となっている。
つまりネストされた方のルーティングには引数に@user
が必要となる。
Prefix | Verb | URI Pattern | Controller#Action |
---|---|---|---|
new_user_micoropost | GET | /users/:user_id/micoroposts/new(.:format) | micoroposts#new |
user | GET | /users/:id(.:format) | users#show |
方法
new_user_micoropost
の引数に@user
を追加する。
user/show.html.erb
<div class="top-wrapper">
<%= link_to "食材を登録する", new_user_micropost_path(@user) %>
</div>
参考