【问题标题】:FasterCSV importer to DataMapper model - No rows insertedFasterCSV 导入器到 DataMapper 模型 - 没有插入行
【发布时间】:2010-09-27 21:26:56
【问题描述】:

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

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

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

【问题讨论】:

    标签: ruby csv datamapper fastercsv


    【解决方案1】:

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

    我猜有两个问题

    • 您打算使用的分隔符是“\t”而不是“/t”
    • 您没有使用 row_data 来填充数据映射器对象

    这应该会更好:

    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
    

    【讨论】:

    • 谢谢,我使用了您的版本,使用正确的制表符分隔符并使用正确的方式从 row_data 中查找项目。虽然仍然没有得到任何进口。无论如何要让 FasterCSV 生成日志,还是如果数据错误会出错?
    • 是的,您可以在 foreach 行之后添加一个“puts row_data.inspect”,以便跟踪 row_data 包含的内容。 (顺便说一下,“\t”表示您的字段是制表符分隔的,可以吗?)
    • 更正它是制表符分隔的,FasterCSV 的示例行输出确认它在读取时为每一列分配了正确的值。只是保存方法似乎没有进入 DataMapper。
    • 由于所有字段似乎都是必需的,它可能会因为实例无效而失败。你确定它们都被填满了(检查有效的?方法)
    • 好的,我将模型更改为允许空值,然后只导入标题。 SQLite 表只反映一个 ID 和 Title。现在收到错误:'tests.description 可能不是 NULL (DataObjects::IntegrityError)'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-30
    • 2018-01-26
    • 1970-01-01
    • 2011-10-27
    相关资源
    最近更新 更多