Adam White
Adam White

Reputation: 1136

Converting a string to integer in CSV import on Rails

I've a rake task where I import CSV data into a database via Rails.

I want a specific column (specifically, row[6] below) to be rendered as an integer. However, everything I try returns that value as a string.

Below is the rake task:

require 'csv'
namespace :import_site_csv do
  task :create_sites => :environment do
    CSV.foreach('../sites.csv', :headers => true) do |row|
        row[6] = row[6].to_i
        Site.create!(row.to_hash)
    end
  end
end 

Does anyone have an idea how I might do this? Thanks!

Upvotes: 2

Views: 1592

Answers (1)

Ilija Eftimov
Ilija Eftimov

Reputation: 820

You are making one small (but important) mistake here.

When you call CSV.foreach('../sites.csv') each of the rows will be an array of the values in that particular row. That would allow you to access the data you need, in the way you do it now - row[6].

But, when you add the :headers => true option to CSV.foreach, you will not get an array of values (row will not be an array). Instead, it will be a CSV::Row object (docs). As you can read in the documentation:

A CSV::Row is part Array and part Hash. It retains an order for the fields and allows duplicates just as an Array would, but also allows you to access fields by name just as you could if they were in a Hash.

For example, if you have a column with the name Title in the CSV, to get the title in each of the rows, you need to do something like:

CSV.foreach('file.csv', :headers => true) do |row|
    puts row['Title']
end

Since I do not know the structure of your CSV, I cannot tell you which key you should use to get the data and convert it to an Integer, but I think that this should give you a good idea of how to proceed.

Upvotes: 1

Related Questions