如何使用字符串数组一次创建多个 ActiveRecord 对象?

How use an array of strings to create multiple ActiveRecord objects at once?

我有一个字符串数组:

days = ["Monday", "Tuesday", "Wednesday"]

我想在数据库中创建一个以每一个命名的一天:

days.each do |day|
  Day.create(name: day)
end

然而,这并不那么可爱。过去,我已经能够通过使用 splat 将它们传递到 attr_accessor 来清理属性列表:

attr_accessor *ATTRIBUTES

我希望能够做这样的事情:

Day.create(name: *days)

ActiveRecord 是否有类似的接口可用?

您可以一次创建它们:

Day.create(days.map { |day| {name: day} })

create 提到的文档:

Creates an object (or multiple objects) and saves it to the database, if validations pass. The attributes parameter can be either a Hash or an Array of Hashes.