larkfofty
larkfofty

Reputation: 85

Nil attributes while importing csv into rails database

I am learning Ruby on Rails and in the process I am creating a sample app that takes data from a csv file (information involving Chicago homicide victims), saves the data into the database, and displays this information to the user.

I am grabbing dates from each row of the .csv file, and I am encountering an issue where seemingly random dates will appear as 'nil' in the database but others will get imported properly. I am also grabbing Name and Age attributes, and these are getting imported correctly and without issue. It is only the dates I am having trouble with

Here is the model which I am using:

class CreateVictims < ActiveRecord::Migration
  def change
    create_table :victims do |t|
      t.string :name
      t.integer :age
      t.date :date

      t.timestamps
    end
  end
end

And here is the rake task I am using to import the data:

require 'csv'
namespace :import_victims_csv do
  task :create_victims => :environment do
    csv_text = File.read('public/seed_data/2013all.csv')
    csv = CSV.parse(csv_text, :headers => true)
    csv.each do |row|
        Victim.create!(date: row[1], age: row[5], name: row[8]) 
    end
  end
end

I'd say about 50% of the dates will be imported correctly, but the other 50% will just result in 'nil'. The source .csv file has the dates listed for all of the names.

For reference, here is a link to the csv file I am importing from: CSV

Upvotes: 0

Views: 513

Answers (1)

lach_wright
lach_wright

Reputation: 36

Looking at your dataset, it seems that the dates are in the format mm/dd/yyyy, according to this question/answer parsing of that format is no longer supported. So perhaps you could try reformatting the date prior to creating the model:

csv.each do |row|
    formatted_date = Date.strptime row[1], '%m/%d/%Y'
    Victim.create!(date: formatted_date, age: row[5], name: row[8]) 
end

Upvotes: 1

Related Questions