【Rails】Validation failed ... must existというエラーの解決法
困ったこと
class User < ApplicationRecord has_many :posts, dependent: :destroyend
class Post < ApplicationRecord belongs_to :userend
Railsにて、1対多の関係にあるUser
モデルとPost
モデルのクラスを作っていた。
ActiveRecord::RecordInvalid (Validation failed: Lost must exist):
すると上のようなエラーが出た。
解決法
class Post < ApplicationRecord belongs_to :user belongs_to :user, optional: trueend
関連付けメソッドの引数にoptional: true
を記述する。
原因
class User < ApplicationRecord has_many :posts, dependent: :destroyend
class Post < ApplicationRecord belongs_to :user, optional: trueend
先ほど例として挙げたモデルクラスの場合、Post
テーブルの外部キーであるuser_id
というカラムは、自動でNOT NULL
になる。
そこでoptional: true
を指定し、その外部キーをnullable
にしてあげることでバリデーションに引っかからなくなる。