0

我正在关注 Railcast 教程https://www.youtube.com/watch?v=_NSBm_Q431Y&t=487s,使用 gem roo 将使用 excel 文件的数据导入数据库。导入和导出数据工作正常,但在导入关系数据时它向我显示以下错误:

unknown attribute 'PzaXCja' for Producto.
Extracted source (around line #73):

      row = Hash[[header, spreadsheet.row(i)].transpose]
      producto = find_by_Clave(row["Clave"]) || new
      producto.attributes = row.to_hash.slice(*row.to_hash.keys) 
      producto.save!
    end
  end

这是我在“producto”模型中的方法:

  has_one :productosxpza, class_name: "Productosxpza", foreign_key: "Producto"
  accepts_nested_attributes_for :productosxpza

  def self.to_csv(options = {})#exportar
    CSV.generate(options) do |csv|
      csv << column_names
      all.each do |producto|
        csv << producto.attributes.values_at(*column_names)
      end
    end
  end

  def self.import(file)#importar
    spreadsheet = open_spreadsheet(file)
    header = spreadsheet.row(1)
    (2..spreadsheet.last_row).each do |i|
      row = Hash[[header, spreadsheet.row(i)].transpose]
      producto = find_by_Clave(row["Clave"]) || new
      producto.attributes = row.to_hash.slice(*row.to_hash.keys) #*row.to_hash.keys para rails 4 que sustituye el attr_accesible de rails 3
      producto.save!
    end
  end

  def self.open_spreadsheet(file)#importar
    case File.extname(file.original_filename)
     when '.csv' then Roo::Csv.new(file.path, packed: false, file_warning: :ignore)
     #when '.xls' then Roo::Excel.new(file.path, packed: false, file_warning: :ignore)
     when '.xlsx' then Roo::Excelx.new(file.path, packed: false, file_warning: :ignore)
     #else raise "Unknown file type: #{file.original_filename}"
     else raise "El formato debe ser .xlsx ó .csv"


     end
  end
4

1 回答 1

1

如果我理解正确,您想productosxpza通过 producto 设置属性,对吗?这应该有效。

producto.productosxpza_attributes = { ... }
于 2017-01-25T06:15:22.330 回答