【问题标题】:unknown attribute in rails 5rails 5中的未知属性
【发布时间】: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


【解决方案1】:

看起来您要设置的属性是"samosa ",后面有一个空格。该属性应该只是"samosa",没有空格。我猜你的电子表格标题是空间的来源。

【讨论】:

  • 这是我发现的问题,除非我看到哈希,否则我无法找到问题所在
猜你喜欢
  • 1970-01-01
  • 2017-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多