LoginSignup
0
0

More than 1 year has passed since last update.

【422 Unprocessable Entity 】のバリデーションエラー、外部キー制約が原因でした。

Posted at

コードを書いてテストを実行したら「422 Unprocessable Entity」というエラーが出ました。
ググってみたらバリデーションエラーみたいです。
そして、自分の場合は外部キー制約の書き方に問題がありました。

環境

  • Ruby 2.6.3
  • Ruby on Rails 6.0.1

結果

modelの外部キー制約のチェックを任意にしてあげる。

前提

利用者(User)が車を1台持っていたり持っていなかったりする状況でした。

class User < ActiveRecord::Base
  has_one :car
end

class Car < ActiveRecord::Base
  belongs_to :user
  # ↑ここが違っていた。
end

この状況だとCarモデルにuser_idがセットされていないとバリデーションエラーが発生します。
そのため、利用者が車を持っていない場合に422エラーが発生していました。

解決

optional: trueを追加してuser_idの存在を任意にしてあげます。

class Car < ActiveRecord::Base
  belongs_to :user, optional: true #<-追加
end
0
0
1

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