【问题标题】:Rails import from csv to modelRails 从 csv 导入模型
【发布时间】:2012-04-12 10:41:27
【问题描述】:

我有一个包含表转储数据的 csv 文件,我想使用 rails 将它直接导入到我的数据库中。

我目前有这个代码:

csv_text = File.read("public/csv_fetch/#{model.table_name}.csv")
ActiveRecord::Base.connection.execute("TRUNCATE TABLE #{model.table_name}")
puts "\nUpdating table #{model.table_name}"
csv = CSV.parse(csv_text, :headers => true)
csv.each do |row|
  row = row.to_hash.with_indifferent_access
  ActiveRecord::Base.record_timestamps = false
  model.create!(row.to_hash.symbolize_keys)
end

here..的帮助下

考虑一下我的示例 csv:

id,code,created_at,updated_at,hashcode
10,00001,2012-04-12 06:07:26,2012-04-12 06:07:26,
2,00002,0000-00-00 00:00:00,0000-00-00 00:00:00,temphashcode
13,00007,0000-00-00 00:00:00,0000-00-00 00:00:00,temphashcode
43,00011,0000-00-00 00:00:00,0000-00-00 00:00:00,temphashcode
5,00012,0000-00-00 00:00:00,0000-00-00 00:00:00,temphashcode

但是这段代码的问题是:

  • 它生成 `id' 作为自动增量 1,2,3,.. 而不是 csv 文件。
  • 0000-00-00 00:00:00 的记录的时间戳自动默认为null,并抛出错误,因为created_at 列不能为null...

我有什么方法可以从 csv 导入到模型的通用方式? 还是我必须为每个模型编写自定义代码来手动操作每一行中的属性??

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 activerecord csv data-import


    【解决方案1】:

    对于问题1,我建议你输出row.to_hash.symbolize_keys,例如

    # ...
    csv.each do |row|
      #...
      hash = row.to_hash.symbolize_keys
      Rails.logger.info "hash: #{hash.inspect}"
      model.create!(hash)
    end
    

    查看是否分配了“id”。

    对于问题 2,我认为存储“0000-00-00”而不是 nil 作为日期不是一个好主意。

    【讨论】:

    • 1:yes 'id' 已分配,我已经使用 rails 控制台查看了每个 stmt... 2:在 rails 迁移中,如果默认为表指定 t.timestamps,它会自动生成 created,updated_at具有此默认值且在 sql 中不为空的列
    【解决方案2】:

    提供像“id”这样的字段和时间戳字段也手动解决了它......

    model.id = row[:id]
    

    如果模型中存在 created_at、updated_at 则类似。

    【讨论】:

      猜你喜欢
      • 2013-02-02
      • 1970-01-01
      • 1970-01-01
      • 2014-04-14
      • 1970-01-01
      • 1970-01-01
      • 2016-01-23
      • 2022-01-13
      • 2020-02-14
      相关资源
      最近更新 更多