当我在Ruby on Rails应用程序中导入CSV文件时,会抛出错误。但是,当我将它转换为.txt文件时,它可以正常工作。
我的模特:
class Zip < ActiveRecord::Base
require 'csv'
def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
zip_hash = row.to_hash
puts "==============\n\n"
puts zip_hash // Just to confirm the hash was created
// {"ZIP"=>"00501", "CBSA"=>"35004", "RES_RATIO"=>"0.000000000", "BUS_RATIO"=>"1.000000000", "OTH_RATIO"=>"0.000000000", "TOT_RATIO"=>"1.000000000"}
puts "==============\n\n"
Zip.create!(zip_hash)
end
end
end
控制器:
class ZipsController < ApplicationController
before_action :set_zip, only: [:show, :edit, :update, :destroy][![enter image description here][1]][1]
def index
@zips = Zip.all
end
def import
Zip.import(params[:file])
redirect_to root_url, notice: "Success"
end
end
当我上传.csv文件时,我得到了
ActiveModel::UnknownAttributeError (unknown attribute 'ZIP' for Zip.):
这是我的db文件:
class CreateZips < ActiveRecord::Migration[5.2]
def change
create_table :zips do |t|
t.integer :ZIP
t.integer :CBSA
t.decimal :RES_RATIO
t.decimal :BUS_RATIO
t.decimal :OTH_RATIO
t.decimal :TOT_RATIO
t.timestamps
end
end
end
zips
表的数据库架构:
ActiveRecord::Schema.define(version: 2018_06_19_024458) do
create_table "zips", force: :cascade do |t|
t.integer "ZIP"
t.integer "CBSA"
t.decimal "RES_RATIO"
t.decimal "BUS_RATIO"
t.decimal "OTH_RATIO"
t.decimal "TOT_RATIO"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
我做错了什么?
以下是一些截图: