0

I would like to import csv file into my database. I am using Ruby 1.8.7 and Rails 3.2.13 and the gem 'csv_importer'.

I am going to fetch productname and release_date from csv file

In my controller

 def import
        csv_text = File.read('test.csv')
        csv = CSV.parse(csv_text, :headers => true)
        csv.each do |row|
            puts row  #getting entire values from csv 
            puts row['productname'] #getting error
 end  

If I print row/row[0], I am getting entire values from csv file as

productname,release_date

xxx,yyy

in my log.

If I print row['productname'], I am getting error as can't convert String into Integer.

How can I rectify this error?

2 Answers 2

1

It looks like you are actually expecting the FasterCSV API, which does support a signature like parse(csv_text, :headers => true).

In Ruby version 1.9 the CSV library in stdlib was replaced with the FasterCSV library. Your code looks like it might work straight up in Ruby 1.9+.

If you want to use the FasterCSV style API without upgrading to a newer Ruby, you can grab the gem and use it instead of CSV:

require 'fastercsv'
csv_text = File.read('test.csv')
csv = FasterCSV.parse(csv_text, :headers => true)
csv.each do |row|
  puts row['productname']
end
Sign up to request clarification or add additional context in comments.

Comments

0

From http://ruby-doc.org/stdlib-1.8.7/libdoc/csv/rdoc/CSV.html#method-c-parse:

CSV.parse(str_or_readable, fs = nil, rs = nil, &block)

Parse lines from given string or stream. Return rows as an Array of Arrays.

... so row in your case is an Array. Array[] takes an Integer as argument, not aString`, which is why you're getting the error.

In other words; row['anything'] cannot work, but row[0] and row[1] will give you the values from column 1 and 2 of the row.

Now, in your case, you are actually calling CSV.parse like so:

CSV.parse(csv_text, :headers => true)

Looking at the docs, we see that the second argument to CSV.parse is the field separator. You're passing :headers => true as a field separator. That tells CSV to split each row whenever it encounters the string "headerstrue" - it doesn't, so it doesn't split each row.

If you remove the second argument to CSV.parse you should be closer to what you expect.

1 Comment

Oh, that's what that meant. Updated my answer with even more documentation reading.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.