Last active
August 29, 2015 14:20
-
-
Save JoshCheek/02bd185d164b4a8d0a41 to your computer and use it in GitHub Desktop.
Loading SalesEngine data into ActiveRecord
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
# https://github.com/JoshCheek/playgrounds <-- lots of examples (params, routes, etc) | |
# https://gist.github.com/JoshCheek/985a70527fa11a0123c5 <-- we got mass insertion working! | |
# s_arb <-- set language to ruby, then type that and press tab! | |
require 'active_record' | |
ActiveRecord::Base.establish_connection adapter: 'sqlite3', database: ':memory:' | |
ActiveRecord::Schema.define do | |
self.verbose = false | |
create_table :customers do |t| | |
t.string :first_name | |
t.string :last_name | |
t.timestamps | |
end | |
create_table :invoices do |t| | |
t.integer :customer_id | |
t.integer :merchant_id | |
t.string :status | |
t.timestamps | |
end | |
end | |
class Customer < ActiveRecord::Base | |
has_many :invoices | |
end | |
class Invoice < ActiveRecord::Base | |
belongs_to :customer | |
end | |
require 'csv' | |
def load_csv(name, klass) | |
filename = "/Users/josh/deleteme/sales_engines/sally-justin/data/#{name}.csv" | |
CSV.foreach(filename, headers: true, header_converters: :symbol) { |row| | |
klass.create! row.to_h | |
} | |
end | |
load_csv 'customers', Customer | |
load_csv 'invoices', Invoice | |
Customer.where(last_name: "Ullrich", first_name: 'Brice') | |
# => [#<Customer:0x007fd944da7ee0 | |
# id: 419, | |
# first_name: "Brice", | |
# last_name: "Ullrich", | |
# created_at: 2012-03-27 14:55:51 UTC, | |
# updated_at: 2012-03-27 14:55:51 UTC>] | |
Customer.find_by(id: 999) # => #<Customer id: 999, first_name: "Clementina", last_name: "Hudson", created_at: "2012-03-27 14:58:15", updated_at: "2012-03-27 14:58:15"> | |
.invoices # => #<ActiveRecord::Associations::CollectionProxy [#<Invoice id: 4833, customer_id: 999, merchant_id: 59, status: "shipped", created_at: "2012-03-17 19:58:15", updated_at: "2012-03-17 19:58:15">, #<Invoice id: 4834, customer_id: 999, merchant_id: 75, status: "shipped", created_at: "2012-03-19 10:58:15", updated_at: "2012-03-19 10:58:15">, #<Invoice id: 4835, customer_id: 999, merchant_id: 58, ... | |
.pluck(:id) # => [4833, 4834, 4835, 4836, 4837, 4838, 4839] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment