Created
April 4, 2016 02:57
-
-
Save typesend/27534185bd22aabd740ece5e85c38e2a to your computer and use it in GitHub Desktop.
This file contains 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
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 |
This file contains 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
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