Skip to content

Instantly share code, notes, and snippets.

@wojtha
Created February 2, 2017 22:10
Show Gist options
  • Select an option

  • Save wojtha/d2a36333e79d2cc3dbb15bda28e8760e to your computer and use it in GitHub Desktop.

Select an option

Save wojtha/d2a36333e79d2cc3dbb15bda28e8760e to your computer and use it in GitHub Desktop.
Rails seeds.rb with data in CSV
# https://gist.github.com/arjunvenkat/1115bc41bf395a162084
# https://github.com/peimelo/saudecontrolada/blob/master/db/seeds.rb
require 'csv'
def rescue_error(e, error_num, row, line_num)
p '-------------------------'
p "[error #{error_num}:line #{line_num}]: #{ e } | #{ row.to_hash }"
error_num += 1
end
def load_file(klass)
error_num = 1
line_num = 2
csv_text = File.read(Rails.root.join('db', 'data', "#{klass}.csv"))
csv = CSV.parse(csv_text, headers: true)
p "loading #{klass} ..."
csv.each do |row|
begin
register = klass.find_by_id(row['id'])
if register
register.update_attributes!(row.to_hash)
else
klass.create!(row.to_hash)
end
rescue => e
error_num = rescue_error(e, error_num, row, line_num)
end
line_num += 1
end
p "... done #{klass}"
end
load_file(Reference)
load_file(Unit)
load_file(Exam)
load_file(Valor)
load_file(Food)
if User.count
User.where(gender: 'Feminino').update_all(gender: 'F')
User.where(gender: 'Masculino').update_all(gender: 'M')
end
if Valor.count
Valor.where(gender: 'Feminino').update_all(gender: 'F')
Valor.where(gender: 'Masculino').update_all(gender: 'M')
end
id name
1 milhões/mm³
2 g/dL
3 %
4 fL
5 pg
6 mil/mm³
7 mg/dL
8 mcg/dL
9 U/L
10 ng/dL
11 mcUI/mL
12 mg/L
13 mg/g
14 pg/mL
15 ng/mL
16 mcmol/L
17 mcU/mL
18 U/mL
19 mUI/mL
20 min
21 seg
22 mm/h
23 UI/L
24 UI/mL
25 nmol/L
26 mcg/L
27 mEq/L
28 mg/g de creatinina
29 mg/24h
30 p/ campo (400 x)
31 mL
32 g/24h
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment