Writing to a file via Tempfile in Ruby

The issue is that you're not actually writing csv data to the file. You're sending arrays to the filehandle. I believe you need something like:

Tempfile.open(....) do |fh|
    csv = CSV.new(fh, ...)
    <rest of your code>
end

to properly setup the CSV output filtering.


I prefer to do

tempfile = Tempfile.new(....)
csv = CSV.new(tempfile, ...) do |row|
  <rest of your code>
end

Here's how I did it.

patient_payments = PatientPayment.all

Tempfile.new(['patient_payments', '.csv']).tap do |file|
  CSV.open(file, 'wb') do |csv|
    csv << patient_payments.first.class.attribute_names

    patient_payments.each do |patient_payment|
      csv << patient_payment.attributes.values
    end
  end
end