上传csv文件rails时的未知属性

时间:2017-10-26 13:19:21

标签: ruby-on-rails csv

当我尝试上传csv文件时,收到以下错误消息:

ActiveModel::UnknownAttributeError in KontoumsatzsController#import
unknown attribute 'weg;wertstellung;umsatzart;buchungsdetails;auftraggeber;empfaenger;betrag;saldo' for Kontoumsatz.

我的模特:

class Kontoumsatz < ApplicationRecord
    attr_accessor :weg, :wertstellung, :umsatzart, :buchungsdetails, :auftraggeber, :empfaenger, :betrag, :saldo

    def self.import(file)
        CSV.foreach(file.path, headers: true) do |row|
            Kontoumsatz.create! row.to_hash
        end
    end

end

我的控制器:

  def import
    Kontoumsatz.import(params[:file])
    redirect_to kontoumsatzs_path, notice: "Erfolgreich importiert"
  end

架构表:

create_table "kontoumsatzs", force: :cascade do |t|
    t.integer  "weg"
    t.string   "wertstellung"
    t.string   "umsatzart"
    t.string   "buchungsdetails"
    t.string   "auftraggeber"
    t.string   "empfaenger"
    t.decimal  "betrag"
    t.decimal  "saldo"
    t.datetime "created_at",      null: false
    t.datetime "updated_at",      null: false
  end

我的路线:

  resources :kontoumsatzs do 
    collection { post :import }
  end

我尝试上传的文件是CSV UTF-8(逗号分隔)(.csv)文件。

row.to_hash似乎不起作用。

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

CSV - 以逗号分隔的值。其中的逗号代表',';)

因此,如果您要使用逗号以外的分隔符,则需要指定它。我们使用为CSV.parse的col_sep传递的foreach选项执行此操作。就像这样......

class Kontoumsatz < ApplicationRecord
    attr_accessor :weg, :wertstellung, :umsatzart, :buchungsdetails, :auftraggeber, :empfaenger, :betrag, :saldo

    def self.import(file)
        CSV.foreach(file.path, headers: true, col_sep: ';') do |row|
            Kontoumsatz.create! row.to_hash
        end
    end

end

这可以帮助您解析使用;分隔的CSV文件。