4th*_*ace 2 ruby rake ruby-on-rails
我想使用seeds.rb文件填充Department表.我在表格中只创建了两列.还有三个由rails创建(id,created_at,updated_at).
当我运行时rake db:seed,我收到以下错误:
ArgumentError:参数数量错误(3为0..1)
这是seeds.rb文件的样子:
departments = Department.create([{ depttitle: 'dept 1' }, { deptdescription: 'this is the first dept' }],
[{ depttitle: 'dept 2' }, { deptdescription: 'this is the second dept' }],
[{ depttitle: 'dept 3' }, { deptdescription: 'this is the third dept' }])
Run Code Online (Sandbox Code Playgroud)
我是如何创建数组或其他东西的问题?
小智 7
它不起作用的原因是你实际上传递了三个数组,每个数组中有两个哈希值.
将单个数组传递给#create方法,并为要创建的每个记录使用单个哈希.例如:
Department.create([{ deptitle: 'dept 1', deptdescription: 'this is the first dept' },
{ depttitle: 'dept 2', deptdescription: 'this is the second dept' }])
Run Code Online (Sandbox Code Playgroud)
但是,不是"创建数组",而是使用简单的循环来创建Department记录.
10.times do |x|
Department.create({deptitle: "dept #{x}", deptdescription: "this is the #{x} department"})
end
Run Code Online (Sandbox Code Playgroud)
在我看来,它看起来更干净,占用更少的地方,如果你需要,更容易更改种子记录的数量.
要从数字创建数字(对于"这是Xst dept"句子),您可以使用人性化的宝石.
| 归档时间: |
|
| 查看次数: |
2997 次 |
| 最近记录: |