Rails FasterCSV “unquoted fields do not allow \r or \n”

痴心易碎 提交于 2019-12-18 05:03:19

问题


I'm having an issue with FasterCSV and my rake db:seeds migration. I get the error: "rake aborted! Unquoted fields do not allow \r or \n (line 2)" on the following seeds.rb data:

require 'csv' 

directory = "db/init_data/"

file_name = "gardenzing020812.csv"
path_to_file = directory + file_name
puts 'Loading Plant records'
# Pre-load all Plant records
n=0
CSV.foreach(path_to_file) do |row|
  Plant.create! :name => row[1],
  :plant_type => row[3],
  :group => row[2],
  :image_path => row[45],
  :height => row[5],
  :sow_inside_outside => row[8]
n=n+1
end                 

I've searched for a solution to this problem and have discovered that for a lot of folks it's a UTF-8 encoding problem. I've tried requiring iconv and :encoding => 'u', but that then gives me the error "invalid byte sequence in UTF-8".

I'm a newbie, and I can't figure out if it's really an encoding issue that I need to crack (which I've been trying to do unsuccessfully and if so, I could really use some guidance) or, more likely I feel, that I've made a simple misstep and done something wrong with the way I've set up seeds.rb and possibly my excel -> csv file. There's no bad or awkward data in the csv file. It's simple one-word strings, text and integers. Please help!


回答1:


It was as simple as clearing all the formatting off in the csv. Excel seems to have a habit of retaining a lot of the formatting after saving in a csv file, which was causing the failure. After I copied and pasted all the data with no formatting in a new csv file, it was fine.




回答2:


Use String.encode(universal_newline: true) instead gsub. It converting CRLF and CR to LF # Always break lines with \n




回答3:


I do not have enough reputation to comment, but I wanted to say that I have been looking this error across the web day and night for a long time and finally found the solution in the comments, by mu is too short.

I finally got it to work when I put quotes around all of my values.

EDIT: Link to answer!!! Rails FasterCSV "unquoted fields do not allow \r or \n"



来源:https://stackoverflow.com/questions/9200175/rails-fastercsv-unquoted-fields-do-not-allow-r-or-n

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!