Help us understand the problem. What is going on with this article?

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

はじめに

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

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away