Goal: I would like to export a ruby hash to CSV
Challenge: I keep getting the error: 'undefined method `to_csv' for # Did you mean? to_s'.
Approach: I'm making a call to Stripe, receive JSON back, sort the data and end up with a hash like this:
{"33"=>{:name=>"John Doe", :currency=>"eur", :total=>18748}, "31"=>{:name=>"Jane Doe", :currency=>"eur", :total=>7222}}
Ideally, I would like to export that hash to CSV so it can be imported to Excel or Google Sheets.
Recurring_revenue.html.slim:
= link_to 'Download CSV', recurring_revenue_path(format: 'csv'), class: 'btn btn-success'
Pages controller:
@invoices = Stripe::Invoice.list(
paid: true,
expand: ['data.subscription'],
limit: 100,
date: {
gte: params[:start_date],
lte: params[:end_date]
}
)
@coaches = {}
@invoices.auto_paging_each do |invoice|
@coaches[invoice.subscription.metadata.coach_id] ||= {
name: invoice.subscription.metadata.coach,
currency: invoice.subscription.plan.currency,
total: 0
}
@coaches[invoice.subscription.metadata.coach_id][:total] ||= 0
@coaches[invoice.subscription.metadata.coach_id][:total] += invoice.total
end
respond_to do |format|
format.html
format.csv { send_data(@coaches.to_csv) }
end
Page.rb
class Page < ApplicationRecord
def self.to_csv
attributes = %w{id email name}
CSV.generate(headers: true) do |csv|
csv << attributes
all.each do |user|
csv << attributes.map{ |attr| user.send(attr) }
end
end
end
end
I have added include "csv"
in application.rb. Can anybody have a look and let me know what I'm doing wrong?