FasterCSV导入器到DataMapper模型 - 没有插入行

时间:2010-09-27 21:26:56

标签: ruby csv datamapper fastercsv

我有一个模型(称为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

我使用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

运行导入程序时没有出现错误。 SQLite表中没有插入任何内容。

我错过了一些明显的东西吗? (该表存在于目标数据库中,字段名称与我文件中的标题相同。

1 个答案:

答案 0 :(得分:2)

更新2014/11/19:FasterCSV已被删除。现在应该使用Ruby标准库CSV。只需将所有FasterCSV替换为CSV

我猜有两个问题

  • 您打算使用的分隔符是“\ t”而不是“/ t”
  • 您没有使用row_data填充datamapper对象

这应该更好:

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