从数组创建模型实例

时间:2018-02-11 17:53:36

标签: ruby-on-rails ruby ruby-on-rails-5

我有一个2D数据数组,需要创建新的Measurement模型实例。什么是最好的方法呢?

简化数组:

=> [{"Date"=>"02/03/2017 11:46:11",
  "Location"=>"Sissach",
  "Serial Number"=>460631,
  "Air Humiditiy (%)"=>27.5,
  "Air Temperature (°C)"=>17.4},
{"Date"=>"02/03/2017 11:46:21",
  "Location"=>"Sissach",
  "Serial Number"=>460632,
  "Air Humiditiy (%)"=>27.2,
  "Air Temperature (°C)"=>17.7}}]

任何用于自动将数据转换为数据库类型数据的gem?谢谢你的时间。

1 个答案:

答案 0 :(得分:4)

考虑您的模型Measurement具有下一个结构:

Measurement(
  id: integer,
  date: datetime,
  location: string,
  serial_number: integer,
  humidity: float,
  temperature: float,
  created_at: datetime,
  updated_at: datetime
)

您可以轻松迭代哈希数组和每个元素,创建一个新的度量记录,如:

[
  { "date"=>"02/03/2017 11:46:11", "location"=>"Sissach", "serial_number"=>460631, "humidity"=>27.5, "temperature"=>17.4 },
  { "date"=>"02/03/2017 11:46:21", "location"=>"Sissach", "serial_number"=>460632, "humidity"=>27.2, "temperature"=>17.7 }
].each do |measurement|
  Measurement.create(
    location:      measurement['location'],
    serial_number: measurement['serial_number'],
    date:          measurement['date'],
    humidity:      measurement['humidity'],
    temperature:   measurement['temperature']
  )
end

或者正如@ 7urkm3n所指出的那样,只要通过散列数组,它就会以相同的方式工作。

如果您需要执行任何额外操作,或者您想首先初始化模型对象,然后检查尝试保存的记录是否成功,请考虑该块。