尝试在我的 Rails 应用程序中导入 CSV 文件时,出现错误 UTF-8 中的无效字节序列
。一切正常,直到我添加了一个 gsub
方法来将其中一个 CSV 列与我的数据库中的一个字段进行比较。
当我导入 CSV 文件时,我想检查每一行的地址是否包含在特定客户端的不同地址数组中。我有一个带有 alt_addresses
属性的客户端模型,其中包含客户端地址的几种不同可能格式。
然后我有一个引用模型(如果您熟悉本地 SEO,您就会知道这个术语)。引用模型没有地址字段,但它有一个 nap_correct?
字段(NAP 代表“姓名”、“地址”、“电话号码”)。如果 CSV 行的名称、地址和电话号码与我在该客户的数据库中拥有的相同,则该引用的 nap_correct?
字段将设置为“正确”。
下面是我的引用模型中的 import
方法:
def self.import(file, client_id)
@client = Client.find(client_id)
CSV.foreach(file.path, headers: true) do |row|
@row = row.to_hash
@citation = Citation.new
if @row["Address"]
if @client.alt_addresses.include?(@row["Address"].to_s.downcase.gsub(/\W+/, '')) && self.phone == @row["Phone Number"].gsub(/[^0-9]/, '')
@citation.nap_correct = true
end
end
@citation.name = @row["Domain"]
@citation.listing_url = @row["Citation Link"]
@citation.save
end
end
下面是 alt_addresses
属性在我的客户端模型中的样子:
def alt_addresses
address = self.address.downcase.gsub(/\W+/, '')
address_with_zip = (self.address + self.zip_code).downcase.gsub(/\W+/, '')
return [address, address_with_zip]
end
我正在使用 gsub
重新格式化 CSV 中的地址列以及我的客户端数据库表中的字段,以便我可以比较这两个值。这就是问题所在。一旦我添加了 gsub
方法,我就开始收到无效的字节序列错误。
我正在使用 Ruby 2.1.3。我注意到我在搜索 Stack Overflow 时发现的很多类似错误都与旧版本的 Ruby 相关。
最佳答案
使用encoding
选项指定编码:
CSV.foreach(file.path, headers: true, encoding: 'iso-8859-1:utf-8') do |row|
# your code here
end
关于ruby-on-rails - Rails 导入 CSV 错误 : invalid byte sequence in UTF-8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33059837/