我正在Windows上运行Rails 5.2。我按照@Tom De Leu(Ruby on Rails - Import Data from a CSV file)的建议将CSV数据导入到表中,如下所示:
task :import_currencies => :environment do
require 'csv'
filename = File.join Rails.root, "lib/tasks/forex20sep2018.csv"
CSV.foreach(filename, :headers => true) do |row|
Currency.create!(row.to_hash)
end
end
CSV本身如下所示:
code,name,symbol
AED,UAE Dirham,د.إ
ALL,Lek,Lek
AMD,Armenian Dram,Lek
ANG,Netherlands Antillean Guilder,ƒ
...
但是当我运行rake任务时:
rails import_currencies
由于以下错误而失败:
rails aborted!
ActiveModel::UnknownAttributeError: unknown attribute 'code' for Currency.
所以我修改了我的代码,如下所示:
task :import_currencies => :environment do
require 'csv'
filename = File.join Rails.root, "lib/tasks/forex20sep2018.csv"
CSV.foreach(filename, :headers => true) do |row|
c = Currency.new
c.code = row[0]
c.name = row[1]
c.symbol = row[2]
c.save
puts c.errors.full_messages
end
end
这运行得很好。麻烦在于它既不灵活也不优雅,所以我想知道为什么原始代码不起作用。
(FWIW,我尝试如下更改CSV标头:
'code', 'name', 'symbol'
"code", "name", "symbol"
:code, :name, :symbol
这些都不起作用。
@Vishal询问表格:
create_table "currencies", force: :cascade do |t|
t.string "name"
t.string "code"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "symbol"
t.index ["code"], name: "index_currencies_on_code"
end
经过很少的建议,我刚刚制作了一个带有一条记录的虚拟CSV:
code,name,symbol
AAA,Dollar,$
并运行以下代码:
task :import_currencies_org => :environment do
require 'csv'
filename = File.join Rails.root, "lib/tasks/forex20sep2018dummy.csv"
CSV.foreach(filename, :headers => true) do |row|
puts row.to_hash
Currency.create!(row.to_hash)
end
end
...仍然出现此错误: