找到你要的答案

Q:ActiveRecord create: pass in an array of attributes

Q:他创建:在属性数组传递

I would like to know if there is a Rails way to create multiple records by passing in an array of attributes.

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?

我想知道,如果有一个Rails的方法来创建多个记录,通过在一个数组属性。

例如,而不是

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)

我想做点什么:

MyModel.create!(attr_1: some_attr, attr_2: [1,2,3,4])

但它不工作。是否有类似的方式来实现这个没有循环?

answer1: 回答1:

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.

 MyModel.create([{attr_1: some_attr, attr_2: 4}, {attr_1: some_attr, attr_2: 5}])

根据文件,你可以从一个数组的创建记录的哈希值:

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.

 MyModel.create([{attr_1: some_attr, attr_2: 4}, {attr_1: some_attr, attr_2: 5}])
ruby-on-rails  activerecord