Rails:从CSV导入ActiveRecord为模型

时间:2016-06-28 15:12:28

标签: ruby-on-rails ruby csv activerecord

我是Rails的新手,我正在进行简单的数据库导入,但无法解决错误。

我在CSV中有这样的数据:

"Symbol","Name","LastSale","MarketCap","IPOyear","Sector","industry","Summary Quote",
"DDD","3D Systems Corporation","12.95","$1.45B","n/a","Technology","Computer Software: Prepackaged Software","http://www.nasdaq.com/symbol/ddd",

我使用以下命令为条目创建模型:

bin/rails generate model Companies Symbol:string Name:string LastSale:string MarketCap:string IPOyear:string Sector:string Industry:string SummaryQuote:string

...我运行db:migrate,然后尝试使用此rake任务将数据导入模型:

  task :populate => :environment do
    #http://stackoverflow.com/questions/4410794/ruby-on-rails-import-data-from-a-csv-file
    CSV.foreach("companylist.csv", :headers => true) do |row|
      Company.create!(row.to_hash)
    end
  end

这会导致错误:

rake aborted!
ActiveRecord::UnknownAttributeError: unknown attribute 'industry' for Company.

然而,“公司”模型是在行业惯例的基础上创建的 - 我不知道如何继续。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

我认为您需要检查表格字段名称,我认为表格中的字段名称是'行业'而不是工业。 最好