我有一个种子文件将一些测试数据播种到我的系统中。
fnames = ["Adam", "Benjamin", "Caleb", "Daniel", "Frank", "Gideon"]
lnames = ["Smith", "Jones", "Washington", "Jefferson", "Gardener",
"Cooper"]
Student.delete_all
3.times do
nickname = fnames[rand(6)]
name = nickname + " " + lnames[rand(6)]
email = (name + "@foobar.com").gsub(" ", "")
Student.create(name: name, email: email, nickname: nickname)
end
Task.delete_all
task_list = [
[ "First", 540 ],
[ "Second", 850 ],
[ "Third", 905 ],
[ "Fourth", 80000 ]
]
Work.delete_all
task_list.each do |description, points|
work = Work.create
task = Task.create( description: description, points: points )
student = Student.first
student.works << work
student.save
work.task = task
work.save
end
但如果我运行它,那么我会收到此错误:
rails@rails-VirtualBox:~/rails_projects/rails-for-business$ rake db:seed
[RailsAdmin] RailsAdmin initialization disabled by default. Pass SKIP_RAILS_ADMIN_INITIALIZER=false if you need it.
rake aborted!
undefined method `works' for nil:NilClass
/home/rails/rails_projects/rails-for-business/db/seeds.rb:34:in `block in <top (required)>'
/home/rails/rails_projects/rails-for-business/db/seeds.rb:30:in `each'
/home/rails/rails_projects/rails-for-business/db/seeds.rb:30:in `<top (required)>'
/home/rails/.rvm/gems/ruby-2.0.0-p247@railstutorial_rails_4_0/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:222:in `load'
/home/rails/.rvm/gems/ruby-2.0.0-p247@railstutorial_rails_4_0/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:222:in `block in load'
/home/rails/.rvm/gems/ruby-2.0.0-p247@railstutorial_rails_4_0/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:213:in `load_dependency'
/home/rails/.rvm/gems/ruby-2.0.0-p247@railstutorial_rails_4_0/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:222:in `load'
/home/rails/.rvm/gems/ruby-2.0.0-p247@railstutorial_rails_4_0/gems/railties-4.0.0/lib/rails/engine.rb:540:in `load_seed'
/home/rails/.rvm/gems/ruby-2.0.0-p247@railstutorial_rails_4_0/gems/activerecord-4.0.0/lib/active_record/tasks/database_tasks.rb:153:in `load_seed'
/home/rails/.rvm/gems/ruby-2.0.0-p247@railstutorial_rails_4_0/gems/activerecord-4.0.0/lib/active_record/railties/databases.rake:181:in `block (2 levels) in <top (required)>'
/home/rails/.rvm/gems/ruby-2.0.0-p247@railstutorial_rails_4_0/bin/ruby_executable_hooks:15:in `eval'
/home/rails/.rvm/gems/ruby-2.0.0-p247@railstutorial_rails_4_0/bin/ruby_executable_hooks:15:in `<main>'
Tasks: TOP => db:seed
(See full trace by running task with --trace)
我无法找到它中的错误。由于它是一个协作项目,我不知道数据库本身的表是如何连接的。
答案 0 :(得分:4)
似乎未创建Student
条记录(因此,Student.first
会返回nil
)。我想你应该检查验证错误。
答案 1 :(得分:1)
好的,这就是问题所在。我的学生记录没有被创建,所以我按照评论中留下的建议添加了一个!创造之后。
Student.create!(name: name, email: email, nickname: nickname)
这告诉我在尝试种子时我将所需的密码字段留空。所以我改变了
Student.create(name: name, email: email, nickname: nickname, password: "foobar")
并且种子文件工作正常