I'm running Rails 5.2 on Windows. I followed advice from @Tom De Leu (Ruby on Rails - Import Data from a CSV file) to import CSV data into a table as follows:
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
The CSV itself looks like this:
code,name,symbol
AED,UAE Dirham,د.إ
ALL,Lek,Lek
AMD,Armenian Dram,Lek
ANG,Netherlands Antillean Guilder,ƒ
...
but when I run the rake task:
rails import_currencies
it fails with this error:
rails aborted!
ActiveModel::UnknownAttributeError: unknown attribute 'code' for Currency.
So I modified my code as follows:
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
And this runs perfectly well. The trouble is it's neither flexible nor elegant so I'd like to know why the original code didn't work.
(FWIW, I tried changing the CSV header as follows:
'code', 'name', 'symbol'
"code", "name", "symbol"
:code, :name, :symbol
None of these helped at all.)
@Vishal asked for the table:
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
After as few suggestions, I have just made a dummy CSV with one record:
code,name,symbol
AAA,Dollar,$
and running this code:
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
... still get this error: