将数据导入 Rails 时遇到问题,奇怪的循环
我正在尝试将数据导入到 Rails (3.1) 中,并且创建了此 rake 任务来解析 CSV 文件(由 Mac 上的 Excel 生成),
desc "Import users."
task :import_users => :environment do
File.open("users.csv", "r").each do |line|
id, name, age, email = line.strip.split(',')
u = User.new(:id => id, :name => name, :age => age, :email => email)
u.save
end
end
但是当我运行 rake 任务时,仅导入 CSV 文件的第一行。除了第一行之外,它不会迭代文件中的每一行。谁能告诉我为什么?
I am trying to import data into rails (3.1) and I have created this rake task to parse a CSV file (generated by Excel on Mac)
desc "Import users."
task :import_users => :environment do
File.open("users.csv", "r").each do |line|
id, name, age, email = line.strip.split(',')
u = User.new(:id => id, :name => name, :age => age, :email => email)
u.save
end
end
However when I run the rake task, only the first line of the CSV file gets imported. It does not iterate over every line in the file besides the first one. Can anyone tell me why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不确定,但我认为这里发生的是每个代表每个文件而不是每一行。由于只有一个文件,这可能无法按预期工作。我会尝试使用 CSV 解析器:
Not sure, but I think what is happening here is the each is representing each file rather than each line. And as there's only one file, this may not work as expected. I'd try a CSV parser instead:
使用 ruby 解析任何类型的文本文件时,请务必检查编码和/或行结尾,以确保它是 Ruby 喜欢的格式。
在这种情况下,Ruby 不喜欢 Mac OS X 行结束格式,但喜欢 Unix 格式。
When parsing any kind of text file using ruby, be sure to check encoding and/or line endings to make sure it's a format that Ruby likes.
In this case, Ruby disliked the Mac OS X line ending format, but liked the Unix one.