class Invoice < ActiveRecord::Base
act_as_importable do |row, company|
invoice = company.invoices.find_or_initialize_by_name(row[:name].to_s)
vat_in = if row[:client].is_a? String
row[:client]
else
row[:client].to_i
end
client = company.clients.find_by_vat_in(vat_in.to_s)
invoice.client = client
invoice.pay_date = row[:pay_date]
invoice.full_amount = row[:full_amount].to_i
invoice.paid_amount = row[:paid_amount].to_i
invoice.save!
invoice
end
end
The importing in controller looks like:
def save
file = params[:file]
logger.debug file.path
Invoice.transaction do
@invoices = Invoice.import_from(file, current_company)
@invoices.each(&:save)
end
rescue RuntimeError => error
logger.debug error
redirect_to import_company_clients_path, alert: I18n.t('invalid_file')
rescue ActiveRecord::RecordInvalid
redirect_to import_company_clients_path, alert: I18n.t('invalid_record')
else
respond_to do |format|
format.html
format.json { render json: @invoices }
end
end