1

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.

1
  • 3
    Measurement.create(array_here) Commented Feb 11, 2018 at 18:01

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer! I was looking for this. With only .create(array) I need to have all of my array attributes in model. But, this way i don't.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.