LoginSignup
11
9

More than 3 years have passed since last update.

saveできない。Validation failed: # must existの解決方法

Last updated at Posted at 2019-05-14

はじめに

Rails5でサービスを開発していく中でsaveしてもテーブルにデータが入らないという問題が。

解決方法

belongs_to に、optional: true をつけてあげることで、関連先の値を検知しないようにさせる。(Rails5から仕様変更になった。)

follow.rb
class Follow < ApplicationRecord
  belongs_to :user, optional: true
end

これでデータがちゃんと入るようになります。

補足

save,createなどでデータが入らない場合はsave!でエラー内容を確認すべし

参考

(個人メモ)Rails5で関連を定義した時はbelongs_toに気をつける
https://qiita.com/junara/items/ca6f65d2f2a27f185f0e
Validation failed: ◯◯ must existのエラー[Rspec]
https://qiita.com/aoitrain/items/90a1781160485bb95abe

11
9
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
11
9