如何创建 seeds.rb 数组?
How to create seeds.rb array?
我想使用 seeds.rb 文件填充部门 table。我在 table 中只创建了两列。 rails (id, created_at, updated_at) 创建了另外三个。
当我 运行 rake db:seed
时,出现以下错误:
ArgumentError: wrong number of arguments (3 for 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' }])
是我创建数组的方式有问题还是其他问题?
您可以如下所示单独创建记录。
Department.create(depttitle: 'dept 1' , deptdescription: 'this is the first dept')
Department.create(depttitle: 'dept 2' , deptdescription: 'this is the second dept')
它不起作用的原因是您实际上传递了三个数组,每个数组中有两个散列。
将单个数组传递给 #create
方法,并为您要创建的每条记录使用单个散列。
例如:
Department.create([{ deptitle: 'dept 1', deptdescription: 'this is the first dept' },
{ depttitle: 'dept 2', deptdescription: 'this is the second dept' }])
但是您可以使用一个简单的循环来创建部门记录,而不是 'creating an array'。
10.times do |x|
Department.create({deptitle: "dept #{x}", deptdescription: "this is the #{x} department"})
end
在我看来,它看起来更干净,占用的空间更少,而且如果需要的话,更改种子记录的数量也更容易。
要从数字创建数字(对于 "this is the Xst dept" 句子),您可以使用 humanize gem.
我们的做法是这样的:
departments = [
{depttitle: "Title", deptdescription: "description"},
{depttitle: "Title2", deptdescription: "description2"},
{depttitle: "Title3", deptdesctiption: "description3"}
]
然后您可以像这样遍历它们:
departments.each do |department|
Department.create department
end
@Sebastian Brych
的答案是正确的 - 当您应该传递具有多个散列的单个数组时,您正在为每个新记录传递数组。
我想使用 seeds.rb 文件填充部门 table。我在 table 中只创建了两列。 rails (id, created_at, updated_at) 创建了另外三个。
当我 运行 rake db:seed
时,出现以下错误:
ArgumentError: wrong number of arguments (3 for 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' }])
是我创建数组的方式有问题还是其他问题?
您可以如下所示单独创建记录。
Department.create(depttitle: 'dept 1' , deptdescription: 'this is the first dept')
Department.create(depttitle: 'dept 2' , deptdescription: 'this is the second dept')
它不起作用的原因是您实际上传递了三个数组,每个数组中有两个散列。
将单个数组传递给 #create
方法,并为您要创建的每条记录使用单个散列。
例如:
Department.create([{ deptitle: 'dept 1', deptdescription: 'this is the first dept' },
{ depttitle: 'dept 2', deptdescription: 'this is the second dept' }])
但是您可以使用一个简单的循环来创建部门记录,而不是 'creating an array'。
10.times do |x|
Department.create({deptitle: "dept #{x}", deptdescription: "this is the #{x} department"})
end
在我看来,它看起来更干净,占用的空间更少,而且如果需要的话,更改种子记录的数量也更容易。
要从数字创建数字(对于 "this is the Xst dept" 句子),您可以使用 humanize gem.
我们的做法是这样的:
departments = [
{depttitle: "Title", deptdescription: "description"},
{depttitle: "Title2", deptdescription: "description2"},
{depttitle: "Title3", deptdesctiption: "description3"}
]
然后您可以像这样遍历它们:
departments.each do |department|
Department.create department
end
@Sebastian Brych
的答案是正确的 - 当您应该传递具有多个散列的单个数组时,您正在为每个新记录传递数组。