LoginSignup
0
0

More than 1 year has passed since last update.

【Ruby on Rails】ルーティングのネストで発生するActionController::UrlGenerationErrorの解消方法

Last updated at Posted at 2023-02-14

前提条件

  • 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>

参考

0
0
0

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