Oteto Blogのロゴ

【Rails】Validation failed ... must existというエラーの解決法

困ったこと

class User < ApplicationRecord
  has_many :posts, dependent: :destroy
end
class Post < ApplicationRecord
  belongs_to :user
end

Railsにて、1対多の関係にあるUserモデルとPostモデルのクラスを作っていた。

ActiveRecord::RecordInvalid (Validation failed: Lost must exist):

すると上のようなエラーが出た。

解決法

class Post < ApplicationRecord
  belongs_to :user
  belongs_to :user, optional: true
end

関連付けメソッドの引数にoptional: trueを記述する。

原因

class User < ApplicationRecord
  has_many :posts, dependent: :destroy
end
class Post < ApplicationRecord
  belongs_to :user, optional: true
end

先ほど例として挙げたモデルクラスの場合、Postテーブルの外部キーであるuser_idというカラムは、自動でNOT NULLになる。

そこでoptional: trueを指定し、その外部キーをnullableにしてあげることでバリデーションに引っかからなくなる。