0

I am new to Rails, and am doing a simple db import but cannot resolve an error.

I have data like so in a 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",

I create a model for the entries with the following command:

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

...I run db:migrate, and then try to import the data to the model with this rake task:

  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

This results in an error:

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

However, the "Company" model was created with an Industry atrribute--I am not sure how to proceed.

Thank you for the help!

manglano
  • 844
  • 1
  • 7
  • 21
  • 1
    is it because you used uppercase letters for the column names, i.e. `Industry`, not `industry`? – Kris Jun 28 '16 at 15:14
  • 1
    Ruby is case-sensitive. I'm not sure whether CSV's `row.to_hash` does the downcasing of the column names but it seems it does. When the hash reaches your model it tries to assign to the `industry` attribute which is not there. There is the `Industry` one but it doesn't match. – Nic Nilov Jun 28 '16 at 15:15
  • Changing the column names to match the attributes exactly resolves that issue, but creates a new error, `"ActiveRecord::UnknownAttributeError: unknown attribute ' ' for Company."` – manglano Jun 28 '16 at 15:20
  • 1
    Remove ending commas from each line of your CSV. – Aleksei Matiushkin Jun 28 '16 at 15:25
  • Is there a dangling column without a header in your CSV? Check out the output of the `row.to_hash` before creating the model and make sure the structure is as you expect. – Nic Nilov Jun 28 '16 at 15:25
  • @mudasobwa Won't `row.reject { |e| e.strip.empty? }` lead to structure corruption in case a middle column has no value? – Nic Nilov Jun 28 '16 at 15:27
  • @NicNilov Oh, indeed, thanks, my bad. I updated a comment, it anyway won’t fix anything since the problem is _with header_. – Aleksei Matiushkin Jun 28 '16 at 15:28
  • @NicNilov @mudasobwa I inserted `row.delete(nil)` before `Company.create!(row.to_hash) `, which seems to have solved the problem. Thanks! – manglano Jun 28 '16 at 15:35

1 Answers1

0

I think you need to check the table field name, I think the Field name in table is 'Industry' instead of industry. Best