gpt4 book ai didi

ruby-on-rails - ActiveRecord 创建 : pass in an array of attributes

转载 作者:行者123 更新时间:2023-12-04 05:17:42 27 4
gpt4 key购买 nike

我想知道是否有 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])

但它不起作用。有没有类似的方法可以在不循环的情况下实现这一目标?

最佳答案

根据文档,您可以 create 来自散列数组的记录:

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 创建 : pass in an array of attributes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30001103/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com