我有一个csv文件与转储数据的表,我想直接导入到我的数据库使用导轨。导轨从csv导入模型
我目前有这个代码:
csv_text = File.read("public/csv_fetch/#{model.table_name}.csv")
ActiveRecord::Base.connection.execute("TRUNCATE TABLE #{model.table_name}")
puts "\nUpdating table #{model.table_name}"
csv = CSV.parse(csv_text, :headers => true)
csv.each do |row|
row = row.to_hash.with_indifferent_access
ActiveRecord::Base.record_timestamps = false
model.create!(row.to_hash.symbolize_keys)
end
与here帮助..
考虑我的样本CSV:
id,code,created_at,updated_at,hashcode
10,00001,2012-04-12 06:07:26,2012-04-12 06:07:26,
2,00002,0000-00-00 00:00:00,0000-00-00 00:00:00,temphashcode
13,00007,0000-00-00 00:00:00,0000-00-00 00:00:00,temphashcode
43,00011,0000-00-00 00:00:00,0000-00-00 00:00:00,temphashcode
5,00012,0000-00-00 00:00:00,0000-00-00 00:00:00,temphashcode
但与此代码的问题是:
- It正在生成`id'作为自动增量1,2,3,..而不是在 csv文件中。
- 为那里是
0000-00-00 00:00:00
默认为自动空,抛出错误作为列created_at不能为空记录的时间戳...
有什么办法,我可以做到这一点在通用的方法来从CSV导入到型号? 或者我将不得不为每个模型编写自定义代码来手动操纵每行中的属性?
1:是的“身份证”被分配,我已经看着每个stmt与轨道控制台... 2:在rails的迁移,如果默认指定表t.timestamps,它会自动生成创建,updated_at列与此默认值,而不是在SQL – 2012-04-12 11:03:52