2009-08-07 100 views
2

我已經使用下面的架構創建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

回答

1

最後兩列將由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

2

要使用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的做法似乎是相同的。