Skip to content

Instantly share code, notes, and snippets.

@jufemaiz
Created September 21, 2016 09:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jufemaiz/6043806705eb4fb906f53468c50c7480 to your computer and use it in GitHub Desktop.
Save jufemaiz/6043806705eb4fb906f53468c50c7480 to your computer and use it in GitHub Desktop.
A tale of Upsert issues
class MeasurementDatum
belongs_to :measurement_point
# Schema
# - measurement_point_id, integer
# - recorded_at, datetime
# - value, double
end
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