gpt4 book ai didi

ruby-on-rails - 将 CSV 文件导入 Rails sqlite3 数据库

转载 作者:数据小太阳 更新时间:2023-10-29 08:35:01 25 4
gpt4 key购买 nike

我使用以下模式创建了 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 数据?

永远感谢

最佳答案

要使用作为标准 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

我没有使用过 fastercsv,但查看了它的 documentation方法似乎是一样的。

关于ruby-on-rails - 将 CSV 文件导入 Rails sqlite3 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1245022/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com