从CSV导入操作之前 [英] Before Action on Import from CSV

查看:176
本文介绍了从CSV导入操作之前的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的CSV导入,其中提供的文件已经损坏(UTF字符)(德语)。

I have a simple CSV import where the provided file is already broken (UTF characters) (German).

例如:列表有:

G%C3%B6tterbote

其中正确的名称应为

Götterbote

我在尝试在导入CSV时强制使用编码。

I'm trying to force the encoding when importing the CSV.

strong>

My Import Action

  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



>我发现这转换字符串成功,但不能成功实现:

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"  

所以基本上我需要一个像 before_action (i guess)..

So basically i need something like a before_action (i guess)..

推荐答案

您不需要之前的操作。

你需要一个pre-prossessor,实际上你需要pre-prossess自己。

You need a pre-prossessor, well actually you need to pre-prossess yourself.

你的CSV包含列。列0,1,2,3等(因为您不使用标头)。

Your CSV comes with columns. Column 0, 1, 2, 3 etc (since you don't use headers).

因此,对于您的文本列,让我们为示例第1,3,5列。

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

这篇关于从CSV导入操作之前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆