reviews_controller.rbのリファクタリング問題 Railsエラー問題の解決するための考え方 その13 ~番外編~

reviews_controller.rbリファクタリング問題

def create

  Review.create(create_params)

  redirect_to controller: :products, action: :index

end

 

private

  def create_params

    params.require(:review).permit(:rate, :review).merge(product_id: params[:product_id], user_id: current_user.id) #(3)

  end

.mergeの中を.merge(product_id: params[:product_id])

とだけにした時に、レビューを登録出来るように修正を行って下さい。

現状のコードだと、誰でもレビューを作成できるようになっている為、ログイン中のユーザーに指定してあげる必要がある。

ログイン中のユーザーのみ新規投稿をするようになるので、最後の文の、user_id: current_user.idnの記述は大丈夫。

正解は下記の通り

def create

  current_user.reviews.create(create_params)

  redirect_to controller: :products, action: :index

end

 

private

  def create_params

    params.require(:review).permit(:rate, :review).merge(product_id: params[:product_id])

  end