2017-10-19 85 views
0

嘿,我想从我的表到数据库中导入一个Excel文件,但我不知道自己是不是工作 获得未知属性:未知属性5

我的表是这样的:

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. 

和哈希值是这样的:

{"name"=>1, "title"=>4, "jalebi"=>7, "samosa "=>9, "s1"=>7, "s2"=>7, "s3"=>7} 
+0

你能告诉你如何定义'Test3'模型吗? 'import1'方法在哪个类中?哪行代码会产生'unknown attribute'错误? – hoffm

回答

1

它看起来像你想的属性设置为"samosa ",并带有尾部空格。该属性应该只是"samosa",不含空格。我猜你的电子表格标题是空间来自哪里。

+0

这是我想出来的问题我找不到什么问题,除非我看到散列 –