0
0

More than 1 year has passed since last update.

Validation failed: 〇〇 must existエラー 解決法

Posted at

結論  

  〇〇の部分のアソシエーションに optional: true を追記してあげる

class Poop < ApplicationRecord
  extend ActiveHash::Associations::ActiveRecordExtensions
  belongs_to :user
  belongs_to :humans, optional: true

 optional: trueとは

外部キーがnillであることを許可してくれるオプションです。

バリデーションにひっからず保存されるようになります。
詳しくは下記リンクに書いてあります。
https://railsguides.jp/association_basics.html#optional

なぜこんな事が起こったか


  def create
    poop = Poop.create(poop_params)
    if poop.save #ここのsaveでhuman_idがないために起こったエラー
      redirect_to root_path
    end
  end

上記の記述ではエラーが表示されずにログでしか確認できないのですが、
save!とすることでValidation failed: 〇〇 must exist
とエラー内容を知る事ができました。
下記save!について詳しく書かれていたページ
https://techacademy.jp/magazine/22082

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