Skip to content

Instantly share code, notes, and snippets.

@typesend
Created April 4, 2016 02:57
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 typesend/27534185bd22aabd740ece5e85c38e2a to your computer and use it in GitHub Desktop.
Save typesend/27534185bd22aabd740ece5e85c38e2a to your computer and use it in GitHub Desktop.
def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
house = find_or_initialize_by(id: row['business_id']) # needed to specify what column to use when finding it
# Explicit mappings is important for maintainability and so it's clear what columns you expect.
house.attributes = {
address: row['address'],
whatever: row['what_ever'],
blah: row['blah_column']
}
# this overwrites all data of any pre-existing records, too, which is probably a bad idea
# what if the spreadsheet contains 3 rows with the same business_id by mistake?
# Now you've just destroyed at least 2 pre-existing records. Better would be to
# find_or_initialize_by the id plus one other attribute that will always be the same for the given id
house.save!
end
end
def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
vacation_home = find_or_initialize_by(:row['business_id']) || new
vacation_home.attributes = row.to_hash
vacation_home.save!
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment