Jorge Najera T
Jorge Najera T

Reputation: 1551

Ruby on Rails - Import CSV file

I'm following this tutorial CSV-FILE-EXPORT-IMPORT-RAILS but something im doing wrong, because i got an silly error when i'm trying to create my object uninitialized constant CuentaContablesController::False. I can read the file without problem, but this error is giving me an headache! Any help will be appreciated!

The method for import in my controller(cuenta_contable_controller.rb) looks like this;

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 

And my model(cuenta_contable.rb) like this

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

Upvotes: 0

Views: 774

Answers (1)

Dave Newton
Dave Newton

Reputation: 160291

You're using True instead of true (likewise for false).

But neither are necessary; the ternary is superfluous and over-parenthesized:

# Ick!
ultimo_nivel = (row[5].downcase=="si") ? (True):(False)

# Pretty!
ultimo_nivel = row[5].downcase == "si"

You might even use a helper to turn row 5 into a boolean and remove it from the mainline code.

Upvotes: 2

Related Questions