问题
I have a simple CSV import where the provided file is already broken (UTF characters) (German).
e.g.: The list has :
G%C3%B6tterbote
where as the right name should be
Götterbote
I'm trying to force the encoding when importing the CSV.
My Import Action
def import
Player.import(params[:file])
redirect_to players_path, notice: "Players Imported successfully"
end
My Import Method
def self.import(file)
SmarterCSV.process(file.path) do |row|
Player.create(row.first)
end
end
I found out that this converts the String successfully, but couldn't implement it successfully:
u = "G%C3%B6tterbote"
=> "G%C3%B6tterbote"
u1 = CGI::unescape(u).force_encoding('UTF-8')
=> "Götterbote"
So basically i need something like a before_action (i guess)..
回答1:
You don't need a before action.
You need a pre-prossessor, well actually you need to pre-prossess yourself.
Your CSV comes with columns. Column 0, 1, 2, 3 etc (since you don't use headers).
So, for your text columns, let's call them for the sake of the example columns 1, 3, 5.
def self.import(file)
text_cols=[1,3,5] #for example
SmarterCSV.process(file.path) do |row|
text_cols.each do |column|
row[column]=CGI::unescape(row[column]).force_encoding('UTF-8')
end
Player.create(row)
end
end
Or simply, for your particular case:
def self.import(file)
SmarterCSV.process(file.path) do |row|
row.first=CGI::unescape(row.first).force_encoding('UTF-8')
Player.create(row.first)
end
end
来源:https://stackoverflow.com/questions/23029367/before-action-on-import-from-csv