Tag Archives: RecordInvalid: Validation failed

[Rails 6] How to deal with ActiveRecord :: RecordInvalid: Validation failed:

symptom

When rails db: seed was executed, the following error was displayed and test data could not be created. (Rails 6.0.3)

Terminal
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: "title",
        price: 500,
        description: "description"
      )
    end

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

Looking at the error message, it seems that Foods has some kind of error.

Solution

It seems that an error occurred because s was added after belongs_to.
In a one-to-n relationship, if 1 is plural, it seems that a validation error will occur.

class Food < ApplicationRecord
    belongs_to :restaurant
end