0

我正在运行一个 rake 任务来导入一些文件属性,我收到一个错误,让我相信为每一行创建的字符串包含某种换行符(例如/n)。

编辑- 已确认换行符是问题。

以下是我的 CSV 文件的示例:

1|type1,type2|category1
2|type2|category1,category2,category3
3|type2,type4|category3,category8

这是我处理它的代码:

namespace :data do
  desc "import"
  task :import => :environment do
    file = File.open(Rails.root.join('lib/assets/data.csv'), 'r')
    file.each do |line|
      attrs = line.split("|")
      foo = Model.find(attrs[0])

      attrs[1].split(",").each do |type|
        foo.add_type!(ModelType.find_by_name(type))
      end

      attrs[2].split(",").each do |category|
        foo.categorize!(ModelCategory.find_by_name(category))
      end
    end
  end
end

ModelTypeModelCategory都是独立的模型,其:through关系Model是用函数Model.add_type!和构建的Model.categorize!

当我运行时rake data:import,一切正常,直到category在第一行结束时达到决赛。不管它是哪个类别,也不管有多少类别attrs[2]——它只会在最后一个失败。这是我收到的错误:

Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id

有关如何解决此问题或避免此错误的任何想法?

4

3 回答 3

2

您可以使用 chomp:

attrs = line.chomp.split("|")
于 2012-05-01T22:44:19.320 回答
0
attrs = line.split("|")
if attrs.length > 0
  foo = Model.find(attrs[0])
  ...
end

您的 CSV 末尾可能有一个空行

更新

file = File.open(Rails.root.join('lib/assets/data.csv'), 'r')
file.split("\r\n").each do |line|

或者

file = File.open(Rails.root.join('lib/assets/data.csv'), 'r')
file.split("\r").each do |line|

或者

file = File.open(Rails.root.join('lib/assets/data.csv'), 'r')
file.split("\n").each do |line|

取决于最初生成 CSV 的方式!

于 2012-05-01T22:26:19.777 回答
0

改用String.encode(universal_newline: true)gsub。它将 CRLF 和 CR 转换为 LF # 总是用 \n 换行

于 2014-12-31T07:39:57.267 回答