Created
September 21, 2016 09:20
-
-
Save jufemaiz/6043806705eb4fb906f53468c50c7480 to your computer and use it in GitHub Desktop.
A tale of Upsert issues
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MeasurementDatum | |
belongs_to :measurement_point | |
# Schema | |
# - measurement_point_id, integer | |
# - recorded_at, datetime | |
# - value, double | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'csv' | |
class MeasurementPoint | |
has_many :measurement_point | |
# Schema | |
# - id, integer | |
# - title, string | |
# Imports a csv of data | |
# expected to have header columns mapping to recorded_at, value | |
# | |
# @param [String] csv | |
# @return [Array<MeasurementDatum>] | |
def import_csv(csv) | |
csv = CSV.parse(csv, headers: true, converters: :numeric) | |
return unless (%w(recorded_at value) - csv.headers).empty? | |
csv.each do |row| | |
MeasurementDatum.upsert({ measurement_point_id: id, recorded_at: row['recorded_at'] },value: row['value'].to_f) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment