简体   繁体   English

从数组创建模型实例

[英]Create model instances from array

I have a 2D array of data and need to create new Measurement model instances. 我有一个二维数据数组,需要创建新的Measurement模型实例。 What is best way to do that? 最好的方法是什么?


Simplified array: 简化数组:

=> [{"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}}]

Any gem for auto convert data to database type of data ? 自动将数据转换为数据库类型的数据有什么用吗? Thanks for your time. 谢谢你的时间。

Considering your model Measurement has the next structure: 考虑您的模型Measurement具有以下结构:

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

You can easily iterate over your array of hashes and on each element, create a new Measurement record, like: 您可以轻松地遍历哈希数组,并在每个元素上创建新的Measurement记录,例如:

[
  { "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

Or as @7urkm3n pointed out, just by passing the array of hashes it would work the same way. 或就像@ 7urkm3n指出的那样,仅通过传递哈希数组就可以以相同的方式工作。

Consider the block in case you need to do any extra operation, or if you want to initialize first a model object and then check if the record trying to be saved has success. 考虑该块,以防您需要执行任何其他操作,或者您想先初始化一个模型对象,然后检查尝试保存的记录是否成功。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM