简体   繁体   English

上载csv文件rails时属性未知

[英]unknown attribute while uploading csv file rails

When I try to upload a csv file I get the following error message: 当我尝试上传CSV文件时,出现以下错误消息:

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

My model: 我的模特:

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

My controller: 我的控制器:

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

Schema table: 模式表:

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

My routes: 我的路线:

  resources :kontoumsatzs do 
    collection { post :import }
  end

The file I am trying to upload is a CSV UTF-8(comma delimited) (.csv) file. 我要上传的文件是CSV UTF-8(逗号分隔)(。csv)文件。

row.to_hash does not seem to work. row.to_hash似乎不起作用。

Any help would be appreciated. 任何帮助,将不胜感激。

CSV - comma separated values. CSV-逗号分隔的值。 Comma in it stands for ',' ;) 其中的逗号代表',';)

So if you are going to use a delimiter other than a comma, you need to specify it. 因此,如果要使用逗号以外的定界符,则需要指定它。 We do this using the col_sep option passed for the foreach of the CSV.parse. 我们使用为col_sepforeach传递的col_sep选项来执行此操作。 Its like this... 就像这样...

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

This should help you parse your CSV file delimited using ; 这应该可以帮助您解析使用分隔的CSV文件; .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM