LoginSignup
2
2

More than 3 years have passed since last update.

Couldn't find Item without an IDというエラーが出た時の対処法

Posted at

idが見つからない時の対処法

自分がエラーが出た時のコントローラーはこちらでした。

order_controller.rb
  def index
    @item = Item.find(params[:id])
    @user_item = UserItem.new
  end

解決方法

結論は、ネストしている時のID名が変わることを知らなかったが故に起きたエラーでした。
rails routesで検索したところ

item_orders GET /items/:item_id/orders(.:format) orders#index

という結果が返ってきたのですが、注意すべきは/:item_id/の部分。
ネストで子要素となっている要素のid名は[:(親要素の名前)_id]に変わるのだそうです。
つまり、正解の記述はこちらになります。

order_controller.rb
  def index
    @item = Item.find(params[:item_id])
    @user_item = UserItem.new
  end

メモ

ネストしている子要素にあたるモデルのID名が変わることが知れて良かった。

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