关于从CSV导入的操作之前
我有一个简单的CSV导入,其中提供的文件已被破坏(UTF字符)(德语)。
例如:该清单有:
G%C3%B6tterbote
正确的名称应该在哪里
Götterbote
我正在尝试在导入CSV时强制编码。
我的导入行动
def import Player.import(params[:file]) redirect_to players_path, notice: "Players Imported successfully" end
我的导入方法
def self.import(file) SmarterCSV.process(file.path) do |row| Player.create(row.first) end end
我发现这会成功转换String,但无法成功实现:
u = "G%C3%B6tterbote" => "G%C3%B6tterbote" u1 = CGI::unescape(u).force_encoding('UTF-8') => "Götterbote"
所以基本上我需要像before_action
(我猜)…
您不需要之前的操作。
你需要一个pre-prossessor,实际上你需要预先进行自我预测。
您的CSV附带列。 列0,1,2,3等(因为您不使用标头)。
因此,对于文本列,让我们为示例列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
或者简单地说,对于您的特定情况:
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