LoginSignup
0
0

More than 3 years have passed since last update.

【Rails6】ActiveRecord::RecordInvalid: Validation failed:の対処法

Posted at

症状

rails db:seedを実施したところ下記エラーが表示されてしまい、テストデータの作成ができませんでした。(Rails6.0.3)

ターミナル
bundle exec rails db:seed
rails aborted!
ActiveRecord::RecordInvalid: Validation failed: Foods is invalid
C:/Users/ユーザー名/environment/プロジェクト名/db/seeds.rb:23:in `block in <main>'
C:/Users/ユーザー名/environment/プロジェクト名/db/seeds.rb:8:in `times'
C:/Users/ユーザー名/environment/プロジェクト名/db/seeds.rb:8:in `<main>'
bin/rails:4:in `<main>'
Tasks: TOP => db:seed
(See full trace by running task with --trace)
seeds.rb
3.times do |n|
    restaurant = Restaurant.new(
      name: "testレストラン_#{n}",
      fee: 100,
      time_required: 10,
    )

    12.times do |m|
      restaurant.foods.build(
        name: "フード名_#{m}",
        price: 500,
        description: "フード_#{m}の説明文です。"
      )
    end

    restaurant.save!
  end
restaurant
class Restaurant < ApplicationRecord
    has_many :foods
end
food
class Food < ApplicationRecord
    belongs_to :restaurants
end

エラーメッセージを見ると、Foodsで何かしらエラーが発生してそうです。

解決方法

belongs_toの後に、sをつけていたためエラーが起きていたようです。
1対nの関係で、1のほうが複数形になると、validateエラーになってしまうようです。

restaurant
class Food < ApplicationRecord
    belongs_to :restaurant
end

参考

【Rails 5】ActiveRecord::RecordInvalid: Validation failed: Hoge must exist
https://qiita.com/jagio/items/5510917f80ca130cbd33

0
0
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
0
0