【发布时间】:2017-10-19 11:23:55
【问题描述】:
嘿,我正在尝试将一个 Excel 文件从我的工作表导入到数据库,但我不知道有什么不工作 获取未知属性:
我的表是这样的:
name title jalebi samosa s1 s2 s3
1 4 7 7 7 7 7
2 5 6 6 6 6 6
3 6 5 5 5 5 5
4 7 4 4 4 4 4
我的迁移是:
class CreateTest3s < ActiveRecord::Migration[5.1]
def change
create_table :test3s do |t|
t.string :name
t.string :title
t.string :jalebi
t.string :samosa
t.string :s1
t.string :s2
t.string :s3
t.timestamps
end
end
end
我在模型中的导入代码是:
def self.import1(file)
spreadsheet = Roo::Spreadsheet.open(file.path)
header = spreadsheet.row(1)
(2..spreadsheet.last_row).each do |i|
row = Hash[[header, spreadsheet.row(i)].transpose]
puts row.to_hash
product = find_by(id: row["id"]) || new
product.attributes = row.to_hash
product.save!
end
end
每当我尝试运行此程序时,我都会收到此错误:
unknown attribute 'samosa ' for Test3.
hash的值是这样的:
{"name"=>1, "title"=>4, "jalebi"=>7, "samosa "=>9, "s1"=>7, "s2"=>7, "s3"=>7}
【问题讨论】:
-
您能说明您是如何定义
Test3模型的吗?import1方法在哪个类中?哪一行代码产生了unknown attribute错误?
标签: ruby-on-rails excel import roo-gem