0
0

More than 3 years have passed since last update.

違うコントローラーのページにredirectするときのパス指定

Last updated at Posted at 2020-09-04

サイトにコメント機能の実装をする際、
comments controllerに

qiita.rb
class CommentsController < ApplicationController
  def create
    Comment.create(comment_params)
    redirect_to item_path(item.id)
  end

  private
  def comment_params
    params.require(:comment).permit(:text).merge(user_id: current_user.id, item_id: params[:item_id])
  end
end

と記述したところ、データベース上に値は保存されてるけど、redirectがエラーとなり、「undefined local variable or method `item' for #< CommentsController:0x00007f7ef315cdd0 >」
と表示された。

[解決策]
redirect_to item_path(item.id)
のitemが何かわかりませんと言われているので、
item = Item.find(params[:id])を追加記述。
そうすると、「idが何かわかりません」と言われたので、item = Item.find(params[:item_id])と書き直したところ通りました。

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