lundi 9 octobre 2017

import records using the gem roo

I am trying to import records to the database using the gem roo using excel files, it works pretty well making use of this tutorial, I am importing nested records belonging to the relation "has_one" when importing again the excel me updates the data, but how can I update the data of those nested resources that are of "has_many"? if every time I import the file with the same data again it re-creates the record, this is my model:

class Cliente < ActiveRecord::Base

  has_many :reldaycli, class_name: "Reldayc", foreign_key: "CodCli"
  accepts_nested_attributes_for :reldaycli, reject_if: proc{|attributes| attributes['RutaId'].blank?}


    def self.import(file,empresa)#importar
      @errors = []
      spreadsheet = open_spreadsheet(file)
      header = spreadsheet.row(1)
      (2..spreadsheet.last_row).each do |i|
        row = Hash[[header, spreadsheet.row(i)].transpose]
        cliente = find_by_IdCli(row["Clave"]) || new
        cliente.attributes = {IdCli: row["Clave"], Nombre: row["Encargado"], NombreCorto: row["Nombre Comercial"], Direccion: row["Calle y N°"], CP: row["C.P"], Colonia: row["Colonia"], Latitud: row["Latitud"], Longitud: row["Longitud"], Referencia: row["Referencia"], Status: row["Activo"], Telefono: row["Teléfono"], Tel2: row["Tel. Celular"], Email: row["Email"], Horario: row["Horario"], Credito: row["Credito"], LimiteCredito: row["Limite Credito"], DiasCreedito: row["Días Credito"], Saldo: row["Saldo inicial"], VisitaObligada: row["Visita Obligada"], FirmaObligada: row["Firma Obligada"], IdEmpresa: empresa}


        cliente.reldaycli_attributes = [{RutaId: row["IdRuta"], idVendedor: row["IdVendedor"], Lunes: row["Lunes"], Martes: row["Martes"], Miercoles: row["Miércoles"], Jueves: row["Jueves"], Viernes: row["Viernes"], Sabado: row["Sábado"], Domingo: row["Domingo"], IdEmpresa: empresa}]



        if cliente.save
          # stuff to do on successful save
         else
           cliente.errors.full_messages.each do |message|
             @errors << "Error fila #{i}, columna #{message}"
           end
         end


      end
      @errors #  <- need to return the @errors array
    end

end

Aucun commentaire:

Enregistrer un commentaire