Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 从CSV导入时属性未知_Ruby On Rails_Ruby_Csv_Ruby On Rails 4 - Fatal编程技术网

Ruby on rails 从CSV导入时属性未知

Ruby on rails 从CSV导入时属性未知,ruby-on-rails,ruby,csv,ruby-on-rails-4,Ruby On Rails,Ruby,Csv,Ruby On Rails 4,我试图在IRB中做到以下几点: file = CSV.read('branches.csv', headers:true) file.each do |branch| Branch.create(attributes:branch.to_hash) end branchs.csv包含一个标题为business\u name的标题,该标题应映射到同名的Branch的属性上,但我看到了错误: ActiveRecord::UnknownAttributeError: unknown attri

我试图在IRB中做到以下几点:

file = CSV.read('branches.csv', headers:true) 
file.each do |branch|
  Branch.create(attributes:branch.to_hash)
end
branchs.csv
包含一个标题为
business\u name
的标题,该标题应映射到同名的
Branch
的属性上,但我看到了错误:

ActiveRecord::UnknownAttributeError: unknown attribute 'business_name' for Branch.
奇怪的是,执行
Branch.create(business_name:'test')
工作正常,没有任何问题

更新:

我认为这与Excel生成的UTF-8 CSV中的文本编码有关,如下面的注释所示。不确定IRB是否提供了任何线索。。。但是我们的标题
业务名称
!=<代码>“业务名称”

2.3.3:348>文件=CSV.read('x.CSV',标题:true)
#
2.3.3:349>将file.first.to_hash.first.first放入
企业名称
2.3.3:350>文件=CSV.read('x.CSV',标题:true)
#
2.3.3:351>将file.first.to_hash.first.first==“业务名称”
假的

只需跳过
属性:
部分。根本不需要它,因为
branch.to_hash
已经返回了您在上一句中描述的格式

file = CSV.read('branches.csv', headers:true) 
file.each { |branch| Branch.create(branch.to_hash) }

感谢您的建议,但不幸的是,在删除
属性后,我看到了完全相同的错误:
分支.to\u hash返回什么?散列中键的编码是什么,在Ruby中使用什么编码?当转换为其字符的十六进制值时,
business\u name
是否在哈希匹配中键入了
business\u name
作为示例(
\u
可能看起来相同,但实际上可能是不同的字符)?您的
Branch
类是什么样子的,涉及的方法(
initialize
create
new
)是否被覆盖?
Branch.to_hash
给了我您想要的东西,比如
{“business\u name=>“Aylesbury”}
。。。我甚至试着用符号来表示钥匙,但没有用。我在
分支
模型上没有重写的方法。我使用UTF-8 CSV和数据库保存了Excel中的文件。yml所有设置为
编码:utf8
的数据库可能在我更新的问题中添加了线索。我不确定我是否相信Excel和非常旧的CSV库能够正确处理utf8。目前我最好的猜测是,您可能在某个地方有编码问题(ASCII或Win xxxx而不是UTF8),或者有人使用特殊类型的下划线来欺骗您。我会将字符串复制到十六进制编辑器中,并研究每个字符和每个字节。给定在两个版本中定义下划线字符的字节数,将有助于识别编码。你们可能会感兴趣的类似问题是:或者疯狂的是,我手工输入了这些标题,所以我真的不知道发生了什么。目前,我只能找到一种方法来解决这个问题,那就是删除标题列,并使用
write\u headers:true,headers:['business\u name']
等手动将它们放入
file = CSV.read('branches.csv', headers:true) 
file.each { |branch| Branch.create(branch.to_hash) }