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
Read More:
- [Solved] liquibase.exception.ValidationFailedException: Validation Failed
- [Exception] javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path validation failed: java.security.cert.CertPathValidatorException: validity check failed
- [Solved] Error reported: org.springframework.validation.BeanPropertyBindingResult
- stm32cubeAI “validation on target “ ERROR [How to Solve]
- WPF path = (validation. Errors) [0]. Errorcontent reports a binding error
- [Solved] Openwrt Pptpd Start Error: validation filed
- How to Solve Error: Heartbeating to master:7182 failed.
- How to Solve Docker ERROR: Service’workspace’ failed to build: ERROR: Service’php-fpm’ failed to build
- How to Solve Error: failed to load response
- How to Solve Springboot Error: Failed to convert value of type
- How to Solve MVC Error: Build failed.
- How to Solve Error: Failed to load ApplicationContext
- How to Solve Docker failed to initialize Error
- How to Solve Logstash error: failed to execute action
- Internalerror: GPU sync failed error (How to Solve)
- How to Solve Application failed to start error
- How to Solve Hyperf Failed to Start Error After Aliyun ACM Installed
- How to Solve NPM update check failed Error
- How to Solve Loadrunner Error: Failed to find .cfg file
- How to Fix Failed to load resource: the server responded with a status of 404()