2

我有一个模型(称为测试):

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'}) 做 |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 表中没有插入任何内容。

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

4

1 回答 1

2

2014 年 11 月 19 日更新:FasterCSV 已被删除。现在应该使用 Ruby 标准库 CSV。只需将所有出现的 替换FasterCSVCSV

我猜有两个问题

  • 您打算使用的分隔符是“\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
于 2010-09-27T21:57:06.603 回答