繁体   English   中英

如何创建seeds.rb数组?

[英]How to create seeds.rb array?

我想使用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' }])

我是如何创建数组或其他东西的问题?

它不起作用的原因是你实际上传递了三个数组,每个数组中有两个哈希值。

将单个数组传递给#create方法,并为要创建的每个记录使用单个哈希。 例如:

Department.create([{ deptitle: 'dept 1', deptdescription: 'this is the first dept' },
                   { depttitle: 'dept 2', deptdescription: 'this is the second dept' }])

但是,您可以使用简单的循环来创建部门记录,而不是“创建数组”。

10.times do |x|
  Department.create({deptitle: "dept #{x}", deptdescription: "this is the #{x} department"})
end

在我看来,它看起来更干净,占用更少的地方,如果你需要,更容易更改种子记录的数量。

要从数字创建数字(对于“这是Xst dept”句子),您可以使用人性化的宝石。

我们这样做的方式如下:

departments = [
   {depttitle: "Title", deptdescription: "description"},
   {depttitle: "Title2", deptdescription: "description2"},
   {depttitle: "Title3", deptdesctiption: "description3"}
]

然后你可以像这样循环遍历它们:

departments.each do |department|
   Department.create department
end

@Sebastian Brych的答案是正确的 - 当你应该传递一个包含多个哈希值的数组时,你会为每个新记录传递数组。

您可以单独创建记录,如下所示。

Department.create(depttitle: 'dept 1' , deptdescription: 'this is the    first dept')
Department.create(depttitle: 'dept 2' , deptdescription: 'this is the second dept')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM