除非在 rails 中播种时保存父错误,否则您无法调用创建
You cannot call create unless the parent is saved error when seeding in rails
我试图用一个简单的种子文件填充我的 SQLite3 数据库,该文件应该在电影 table 中创建一堆电影条目,然后为存储在评论中的电影创建一些评论table.
formats = %w(Beta VHS IMAX HD SuperHD 4K DVD BlueRay)
30.times do
film = Film.create(title: "#{Company.bs}",
director: "#{Name.name}",
description: Lorem.paragraphs.join("<br/>").html_safe,
year: rand(1940..2015),
length: rand(20..240),
format: formats[rand(formats.length)]
)
film.save
(rand(0..10)).times do
film.comments.create( author: "#{Name.name}",
title: "#{Company.bs}",
content: Lorem.sentences(3).join("<br/>").html_safe,
rating: rand(1..5)
)
end
end
一旦我执行 rake db:seed 我不可避免地得到错误
ActiveRecord::RecordNotSaved: You cannot call create unless the parent is saved
并且没有记录添加到电影或评论中
我的 film.rb 文件是
class Film < ActiveRecord::Base
has_many :comments
validates_presence_of :title, :director
validates_length_of :format, maximum: 5, minimum:3
validates_numericality_of :year, :length, greater_than: 0
validates_uniqueness_of :title
paginates_per 4
end
'format' 的长度限制在使用从 'format' 列表
中选择的格式创建电影时引发错误
ActiveRecord::RecordNotSaved: You cannot call create unless the parent is saved
当您尝试保存子关联(评论)但父关联(影片)尚未保存时,会发生这种情况。
好像film
没有保存。查看代码,似乎 film = Film.create(...)
验证失败,因此 film.comments.create(..)
无法继续。
在不知道更多关于哪个验证失败的情况下,我只能说这些。
我建议在 seeds.rb 中的任何地方使用 create!(...)
。如果记录无效,bang 版本将引发异常并有助于防止静默失败。
我试图用一个简单的种子文件填充我的 SQLite3 数据库,该文件应该在电影 table 中创建一堆电影条目,然后为存储在评论中的电影创建一些评论table.
formats = %w(Beta VHS IMAX HD SuperHD 4K DVD BlueRay)
30.times do
film = Film.create(title: "#{Company.bs}",
director: "#{Name.name}",
description: Lorem.paragraphs.join("<br/>").html_safe,
year: rand(1940..2015),
length: rand(20..240),
format: formats[rand(formats.length)]
)
film.save
(rand(0..10)).times do
film.comments.create( author: "#{Name.name}",
title: "#{Company.bs}",
content: Lorem.sentences(3).join("<br/>").html_safe,
rating: rand(1..5)
)
end
end
一旦我执行 rake db:seed 我不可避免地得到错误
ActiveRecord::RecordNotSaved: You cannot call create unless the parent is saved
并且没有记录添加到电影或评论中
我的 film.rb 文件是
class Film < ActiveRecord::Base
has_many :comments
validates_presence_of :title, :director
validates_length_of :format, maximum: 5, minimum:3
validates_numericality_of :year, :length, greater_than: 0
validates_uniqueness_of :title
paginates_per 4
end
'format' 的长度限制在使用从 'format' 列表
中选择的格式创建电影时引发错误ActiveRecord::RecordNotSaved: You cannot call create unless the parent is saved
当您尝试保存子关联(评论)但父关联(影片)尚未保存时,会发生这种情况。
好像film
没有保存。查看代码,似乎 film = Film.create(...)
验证失败,因此 film.comments.create(..)
无法继续。
在不知道更多关于哪个验证失败的情况下,我只能说这些。
我建议在 seeds.rb 中的任何地方使用 create!(...)
。如果记录无效,bang 版本将引发异常并有助于防止静默失败。