【问题标题】:Cannot import completely CSV file无法完全导入 CSV 文件
【发布时间】:2014-05-23 19:24:01
【问题描述】:

我使用此代码将我的 CSV 文件导入表:

def Hotel.import(file)
  allowed_attributes = ["id", "name", "area", "short_name", "zip", "address", "tel", "fax", "staff_name", "information", "created_at", "updated_at"]
  CSV.foreach(file.path, headers: true) do |row|
    product = find_by_id(row["id"]) || new
    product.attributes = row.to_hash.select{ |k,v| allowed_attributes.include? k }
    product.save!
  end
end

def import
  Hotel.import(params[:file])
  redirect_to root_url, notice: "Product Imported."
end

但是,此代码仅将 id、created_at 和 updated_at 字段插入到表中。插入命令显示在这里:

INSERT INTO `hotels` (`created_at`, `updated_at`) VALUES ('2014-04-10 07:50:23', '2014-04-10 07:50:23')

我正在使用 rails 4.0 和 ruby​​ 2.0 来完成这个项目。我仔细检查发现错误,但我在这里找不到任何问题,所以请告诉我我错在哪里?

【问题讨论】:

  • 我找不到任何错误。 row.to_hash.select{ |k,v| allowed_attributes.include? k } 返回什么?
  • 在您的强参数中是否允许使用 allowed_attributes?
  • @Stefan 原始代码是 '*accessible_atributes' 而不是 row.to_hash.select{ |k,v| allowed_attributes.include? k },但是这个原始代码在rails 4中导致错误,然后我搜索并找到了这个解决方案。这段代码让我很困惑。
  • insert p row.to_hash.select{ |k,v| allowed_attributes.include? k }, Kernel#p 检查对象并打印结果,您应该在日志中看到它
  • 我发布的行 (p row.to_hash...) 应该打印一个哈希,类似于 {"id" => "1", ...}

标签: ruby csv ruby-on-rails-4


【解决方案1】:

我发现问题是:当我将文件导出到桌面时,我选择通过 LibreOffice Calc(Ubuntu 13.10) 打开它,所以格式错误。我通过 gedit 文本编辑器打开进行了更改,它工作正常。非常愚蠢的错误!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-25
    • 2018-09-03
    • 2012-06-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多