views:

63

answers:

2

I'm trying to use Ruby's csv module to import the records contained in a csv file to my local table in a Ruby on Rails 3 application.

The table was created through the creation of model Movie.

Here is what I've been executing in console:

require 'csv'
CSV.foreach('public/uploads/VideoTitles2.csv') do |row|
    record = Movie.new(
        :media_format   => row[0], 
        :title          => row[1], 
        :copies_at_home => row[2], 
        :order          => row[3]
    )
    record.save
end

The rows of the csv file match (in data type) the columns they're being passed into. Here is a shortened version of the csv file (VideoTitles2.csv) I'm attempting to import:

"DVD","LEAP OF FAITH",1,1
"DVD","COCOON",1,2
"DVD","TITANIC",1,3

where each record is separated by \n I believe. This csv file was exported from Access and its original file extension was .txt. I've manually changed it to .csv for sake of the import.

The problem is that, after executing the above lines in rails console, I get the following output:

=> nil

The import doesn't seem to happen. If anyone has an idea as to how I could remedy this I'd really appreciate it.

+1  A: 

I don't see the problem. This code snippet returns nil because CSV.foreach returns nil, but this is no indication if the loop is run or not. Did you checked if any Movie was created? did you include any debug lines to follow the process?

You may want to check the output of record.save (or call record.save!), maybe validations errors are preventing the record from being created. Also, if you want the loop to return the created records, you can write this (Ruby >= 1.8.7):

require 'csv'
records = CSV.foreach('public/uploads/VideoTitles2.csv').map do |row|     
    Movie.create!({
        :media_format   => row[0], 
        :title          => row[1], 
        :copies_at_home => row[2], 
        :order          => row[3],
    })
end
tokland
well the model/table movie already exists (i created it ahead of time). however i verified that none of the records were added. as a matter of fact, it resulted in a standard scaffolded controller/view throwing an error
anxiety
A: 

Okay there were two things I had wrong:

  1. The exported csv file should not have quotations around the strings - I just removed them.

  2. Thanks to tokland, the record.save! was necessary (as opposed to the record.save I was doing) - validation errors were preventing the records from being created.

So to conclude, one could just create the following function after creating the model/table Movie:

class Movie < ActiveRecord::Base
  attr_accessible :media_format, :title, :copies_at_home, :order
  require 'csv'

  def self.import_movies()
    CSV.foreach('public/uploads/movies.csv') do |row|
        record = Movie.new(
            :media_format   => row[0], 
            :title          => row[1], 
            :copies_at_home => row[2], 
            :order          => row[3]
        )
        record.save!  
    end
  end
end

Where movies.csv looks like the following:

Blu-ray, Movie 1, 1, 1
DVD, Movie 2, 1, 2
Blu-ray, Movie 3, 1, 3

then call this function in console as such:

Movie.import_movies()

and, as expected, all that would be returned in the console would be:

=> nil

Check your index view (if you've created one) and you should see that the records were successfully imported into the movies table.

anxiety
no control of repeated movies? also, it's good etiquette for a function to return something meaningful. Maybe the array of newly created movies? maybe just the number? note also that new + save! = create!
tokland
yeah very true; I was using it as a one time thing
anxiety