我正在运行一个 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
ModelType和ModelCategory都是独立的模型,其: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
有关如何解决此问题或避免此错误的任何想法?