1

我从Link-=> https://github.com/bparanj/exp.xls下载了使用 ruby​​ on rails导入的代码。Github

设置 apache 服务器后,当我们选择要导入的 .xlsx 文件时,我收到以下错误消息

ActiveModel::UnknownAttributeError in ProductsController#import


 Extracted source (around line #17):


 def self.import(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]

主要product.rb文件

require 'csv'

class Product < ApplicationRecord
  validates_presence_of :price

  def self.to_csv(options = {})
    desired_columns = ["id", "name", "released_on", "price"]
    CSV.generate(options) do |csv|
      csv << desired_columns
      all.each do |product|
        csv << product.attributes.values_at(*desired_columns)
      end
    end
  end

  def self.import(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]
      product = find_by(id: row["id"]) || new
      product.attributes = row.to_hash
      product.save!
    end
  end  

源代码可在 => https://github.com/bparanj/exp中找到

4

0 回答 0