I would like to know if there is a Rails way to create multiple records by passing in an array of attributes.
我想知道是否有一种Rails方法通过传入一组属性来创建多个记录。
For instance, instead of
例如,而不是
MyModel.create!(attr_1: some_attr, attr_2: 1)
MyModel.create!(attr_1: some_attr, attr_2: 2)
MyModel.create!(attr_1: some_attr, attr_2: 3)
MyModel.create!(attr_1: some_attr, attr_2: 4)
I would like to do something like:
我想做的事情如下:
MyModel.create!(attr_1: some_attr, attr_2: [1,2,3,4])
But it does not work. Is there a similar way to achieve this without looping?
但它不起作用。有没有类似的方法来实现这一点没有循环?
1 个解决方案
#1
13
According the documentation you can create
records from an array of hashes:
根据文档,您可以从散列数组中创建记录:
The attributes parameter can be either be a Hash or an Array of Hashes. These Hashes describe the attributes on the objects that are to be created.
attributes参数可以是Hash或Hashes数组。这些哈希描述了要创建的对象的属性。
MyModel.create([{attr_1: some_attr, attr_2: 4}, {attr_1: some_attr, attr_2: 5}])
#1
13
According the documentation you can create
records from an array of hashes:
根据文档,您可以从散列数组中创建记录:
The attributes parameter can be either be a Hash or an Array of Hashes. These Hashes describe the attributes on the objects that are to be created.
attributes参数可以是Hash或Hashes数组。这些哈希描述了要创建的对象的属性。
MyModel.create([{attr_1: some_attr, attr_2: 4}, {attr_1: some_attr, attr_2: 5}])