在 Rails 导入 CSV 期间未知属性 'headers ...'
Unknow attribute 'headers ...' during CSV import on Rails
我遇到了一个问题,因为我尝试在 Mac、
上导入使用 Numbers 创建的 CSV
之前在 Ubuntu 使用 LibreOffice 时一切正常,
当我尝试导入我的 CSV 文件时出现错误
unknown attribute 'adress user_id room_type etc...' for Bien.
我认为它不会检测分隔符并将第一个听众行作为一个字符串。
我的导入函数:
def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
@bien = Bien.create! row.to_hash
@bien.save
end
end
我会知道如何导入文件,以及当我在 Numbers 上创建 CSV 时是否需要更改。
更新
我认为您完全正确,分隔符似乎没有得到遵守,因此 header 行显示为一长串。要进行调试,您可以尝试放入 pry
和 运行 CSV.read(file.path)
以查看转换为 CSV 的整个输出。完成后,您应该能够看到 Numbers 使用什么作为分隔符。
This post suggests Numbers uses semicolons as default separators, so if you define your col_sep: ';'
as an option, that might do the trick. (Ref: CSV docs)。
所以,代码是
def self.import(file)
CSV.foreach(file.path, col_sep: ';', headers: true) do |row|
@bien = Bien.create! row.to_hash
@bien.save
end
end
我遇到了一个问题,因为我尝试在 Mac、
上导入使用 Numbers 创建的 CSV之前在 Ubuntu 使用 LibreOffice 时一切正常,
当我尝试导入我的 CSV 文件时出现错误
unknown attribute 'adress user_id room_type etc...' for Bien.
我认为它不会检测分隔符并将第一个听众行作为一个字符串。
我的导入函数:
def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
@bien = Bien.create! row.to_hash
@bien.save
end
end
我会知道如何导入文件,以及当我在 Numbers 上创建 CSV 时是否需要更改。
更新
我认为您完全正确,分隔符似乎没有得到遵守,因此 header 行显示为一长串。要进行调试,您可以尝试放入 pry
和 运行 CSV.read(file.path)
以查看转换为 CSV 的整个输出。完成后,您应该能够看到 Numbers 使用什么作为分隔符。
This post suggests Numbers uses semicolons as default separators, so if you define your col_sep: ';'
as an option, that might do the trick. (Ref: CSV docs)。
所以,代码是
def self.import(file)
CSV.foreach(file.path, col_sep: ';', headers: true) do |row|
@bien = Bien.create! row.to_hash
@bien.save
end
end