LoginSignup
0
0

More than 1 year has passed since last update.

新規投稿時にundefined method `upload' for nil:NilClassエラーについて

Posted at

解決したいこと

料理投稿サイトで新規投稿画面にてタイトル、紹介文、画像の情報を入力し新規投稿したところundefined method `upload' for nil:NilClassエラーが出て解決をしたい。
前提・・・Active Strage導入済

試して見たこと

データの流れを確認するためにテーブル、モデル、コントローラの記述を一通り確認。
=>これといった間違いはないような感じが。モデルにも has_one_attachedの記述があり問題はなさそう。
コントローラもストロングパラメータは大丈夫。

*/CookOP/app/models/dish.rb

class Dish < ApplicationRecord
  has_one_attached :dish_image
  belongs_to :user#, optional: true
  has_many :comments, dependent: :destroy
  has_many :favorits, dependent: :destroy

end

*/CookOP/app/controllers/dishes_controller.rb

class DishesController < ApplicationController
  def new
    @dish = Dish.new
  end

  def create
    @dish = Dish.new(dish_params)#ここでエラー
    @dish.save
    redirect_to user_path(current_user.id)
  end

  private

  def dish_params
    params.require(:dish).permit(:dish_name, :introduction, :user_id, :dish_image).merge(user_id: current_user.id)

  end

end

解決方法

結局完全にお手上げ状態でメンターの方に見ていただきました。
すると私が前提としていたActive Strageに問題がありました。手順通りに進めてインストールをしたはずだったのに、、、

インストールはしていたけれども必要なものが全て揃っていなかったとのことでした。
以下の手順で進めました。

『手順』
config/environments/development.rbに追記

config.active_storage.service = :local

config直下にstorage.ymlを作成し以下を記述

test:
  service: Disk
  root: <%= Rails.root.join("tmp/storage") %>

local:
  service: Disk
  root: <%= Rails.root.join("storage") %>

これで先ほどのエラーは解決されました。
手順通りに進めてもうまくいかない時はわかりません、、、

以上です。

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