Search code examples
rubycsvdatamapperfastercsv

FasterCSV importer to DataMapper model - No rows inserted


I have a model (called Test):

property :id,           Serial  
property :title,        String,     :length => 255, :required => true
property :description,  String,     :length => 255, :required => true
property :brand,        String,     :length => 255, :required => true
property :link,         String,     :length => 255, :required => true
property :image_link,   String,     :length => 255, :required => true
property :price,        String,     :length => 255, :required => true
property :condition,    String,     :length => 255, :required => true
property :product_type, String,     :length => 255, :required => true

I am importing data from a tab delimited file, using FasterCSV,

FasterCSV.foreach("test.txt", {:headers => true, :quote_char=>'"', :col_sep =>'/t'}) do |row_data|

 row_data = Test.first_or_new(
    'title' =>  :title,
    'description' => :supplier,
    'brand' => :brand,
    'link' => :link,
    'image_link' => :image_link,
    'price' => :price,
    'condition' => :condition,
    'product_type' => :product_type
  )

row_data.save

end

No errors appear, when I run the importer. Nothing appears inserted in SQLite table.

Am i missing something obvious? (The table exists within the target database, and the field names are the same as the headers from my file.


Solution

  • Update 2014/11/19: FasterCSV has been removed. Ruby standard library CSV should now be used intead. Just replace all occurrences of FasterCSV with CSV

    There's two problem i guess

    • the delimiter you intended to use was rather "\t" than '/t'
    • you're not using the row_data to populate the datamapper object

    This should work better:

    FasterCSV.foreach("test.txt", {:headers => true, :quote_char=>'"', :col_sep =>"\t"}) do |row_data|
    
        new_record = Test.first_or_new(
            'title' =>  row_data['title'],
            'description' => row_data['supplier'],
            'brand' => row_data['brand'],
            'link' => row_data['link'],
            'image_link' => row_data['image_link'],
            'price' => row_data['price'],
            'condition' => row_data['condition'],
            'product_type' => row_data['product_type']
        )
        new_record.save
    end