简体   繁体   中英

Create model instances from array

I have a 2D array of data and need to create new Measurement model instances. 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(
  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:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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