如何创建seeds.rb数组?

时间:2015-11-08 19:34:31

标签: ruby-on-rails ruby rake

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

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

3 个答案:

答案 0 :(得分:7)

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

将单个数组传递给#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”句子),您可以使用humanize gem。

答案 1 :(得分:1)

我们这样做的方式如下:

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

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

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

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

答案 2 :(得分:0)

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

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