将CSV文件导入Rails sqlite3数据库

时间:2009-08-07 14:26:02

标签: ruby-on-rails ruby sqlite

我使用以下架构创建了Rails数据库:

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数据?

总是谢谢

3 个答案:

答案 0 :(得分:2)

使用作为标准Ruby库一部分的csv模块:

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

我没有使用fastcsv,但看着它的documentation方法看起来是一样的。

答案 1 :(得分:2)

答案 2 :(得分:1)

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

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

相关问题