[英]Ruby on Rails - Import CSV file
我正在遵循這個教程CSV-FILE-EXPORT-IMPORT-RAILS,但我做錯了,因為當我試圖創建我的對象未初始化的常量CuentaContablesController :: False時,我遇到了一個愚蠢的錯誤。 我可以毫無問題地閱讀該文件,但是這個錯誤讓我很頭疼! 任何幫助將不勝感激!
在我的控制器中導入的方法(cuenta_contable_controller.rb)如下所示;
class CuentaContablesController < ApplicationController
....
def upload(params)
logger.info "**File loaded***"
infile = params[:file].read
n, errs = 0, []
@archivo = []
SV.parse(infile) do |row|
n += 1
# SKIP: header i.e. first row OR blank row
next if n == 1 or row.join.blank?
cuenta_contable = CuentaContable.build_from_csv(row)
if cuenta_contable.valid?
cuenta_contable.save
@archivo << row
else
errs << row
end
end
logger.info errs
flash[:success] = "Las cuentas contables fueron cargadas."
respond_to do |format|
format.html # index.html.erb
format.json { render :json => @archivo }
end
end
我的模型(cuenta_contable.rb)就像這樣
class CuentaContable < ActiveRecord::Base
....
def self.build_from_csv(row)
ultimo_nivel = (row[5].downcase=="si") ? (True):(False)
#cuenta = find_or_initialize_by_cuenta("#{row[0]}-#{row[1]}-#{row[2]}")
# Buscas el archivo existing customer from email or create new
cuenta = CuentaContable.new(:cuenta => "#{row[0]}-#{row[1]}-#{row[2]}",
:descripcion => "#{row[3].titleize}",
:categoria_cuenta => "#{row[4].titleize}",
:ultimo_nivel=> ultimo_nivel)
return cuenta
end
你使用的是True
而不是true
(同樣是false
)。
但兩者都不是必要的; 三元是多余的,過度括號:
# Ick!
ultimo_nivel = (row[5].downcase=="si") ? (True):(False)
# Pretty!
ultimo_nivel = row[5].downcase == "si"
您甚至可以使用幫助器將第5行轉換為布爾值並將其從主線代碼中刪除。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.