Skip to content

Instantly share code, notes, and snippets.

@dtauer
Last active August 29, 2015 14:01
Show Gist options
  • Save dtauer/19155c4cbf49af530d7a to your computer and use it in GitHub Desktop.
Save dtauer/19155c4cbf49af530d7a to your computer and use it in GitHub Desktop.
For Jordan - Populate data from Google Spreadsheet
#Your Current seed.rb code that creates books (the manual way):
Book.create("title" => "A Brief History of Time", "author" => "Stephen Hawking")
Book.create("title" => "Alice in Wonderland", "author" => "Lewis Carroll")
Book.create("title" => "The Lord Of The Rings", "author" => "J.R.R. Tolkien")
Book.create("title" => "The Hobbit", "author" => "J.R.R. Tolkien")
# Firstly, save each tab as a CSV file (a comman separate file)
# To save as a CSV, just go to File > Download As > CSV (for each tab)
# You could put them in a directory on your server
# Then you could do something like this (this one is for the book data):
#include the csv library
require 'csv'
#loop through a csv file. Each "row" in the file will populate the "row" variable in the loop
CSV.foreach("path/to/file.csv") do |row|
# Grab each column from the row and save them as temporary variables
title = row[0]
author = row[1]
price = row[2]
# Now create a book like before, but with your dynamic data
Book.create("title" => title, "author" => author, "price" => price)
end
#Then youd'd do the same code as above for the other CSV file
#
#
#
#
#
#
#
# Here's the example with the upload option
require 'csv'
#Choose a file to upload
csv_data = File.read('...')
#Read the uploaded file (first row are the headers so that's why "headers" are true....because they are included)
books = CSV.parse(csv_data, :headers => true)
books.each do |row|
title = row[0]
author = row[1]
price = row[2]
# Now create a book like before, but with your dynamic data
Book.create("title" => title, "author" => author, "price" => price)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment