导入CSV文件到Rails sqlite3的数据库

问题描述:

我已经使用下面的架构创建Rails的数据库:导入CSV文件到Rails sqlite3的数据库

ActiveRecord::Schema.define(:version => 20090807141407) do 

    create_table "trunks", :force => true do |t| 
    t.integer "npa" 
    t.integer "nxxFrom" 
    t.integer "nxxTo" 
    t.string "trnk" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    end 

end 

在我的CSV文件,我只有前四列(NPA,nxxFrom,nxxTo和trnk)。

如何在导入CSV数据的同时更新最后两列?

总是感谢

+0

如果创建从CSV文件中的每一行ActiveRecord模型,并保存它,然后ActiveRecord的将填充created_at /的updated_at你。你在问如何在Ruby中进行CSV解析? – mikej 2009-08-07 14:30:50

+0

对不起,我是一名新手。 CSV文件是来自服务器的原始数据。你是说我可以以某种方式将其转换为ActiveRecord模型?如果这是可能的,那将会很好 – b1gtuna 2009-08-07 14:34:53

最后两列将由ActiveRecord更新。如果它们存在于模式中,那么在创建对象时,ActiveRecord将为created_at和updated_at添加一个值。对对象的任何修改都会导致updated_at列自动更新。

因此,从CSV导入时只需映射前4列并保存对象。当你检索对象时,你会看到其他两个值也被自动设置。

+0

好的,我是否通过sqlite3命令实用程序导入数据?还是有一个Rails方法来处理这个? 感谢您的帮助! – b1gtuna 2009-08-07 14:40:26

+0

要从CSV导入,那里有宝石。尝试fastercsv。 (fastercsv.rubyforge.org) – Will 2009-08-07 14:40:58

+0

甜蜜!你们是最棒的! – b1gtuna 2009-08-07 14:44:04

要使用csv模块是标准Ruby库的一部分:

require 'csv' 

# row will be an array with the fields in the order they appear in the file 
CSV.open('myfile.csv', 'r') do |row| 
    # assuming the fields in the CSV file are in order npa, nxxFrom, nxxTo, trnk 
    # create and save a Trunk model for each row 
    Trunk.create!(:npa => row[0], :nxxFrom => row[1], :nxxTo => row[2], :trnk => row[3]) 
end 

我没有使用过fastercsv但看着它documentation的做法似乎是相同的。