目标:我想将ruby哈希导出为CSV
挑战:我一直收到错误:'未定义的方法`to_csv'为#你的意思? to_s&#39 ;.
方法:我正在调用Stripe,接收JSON,对数据进行排序,最后得到这样的哈希:
{"33"=>{:name=>"John Doe", :currency=>"eur", :total=>18748}, "31"=>{:name=>"Jane Doe", :currency=>"eur", :total=>7222}}
理想情况下,我想将该哈希导出为CSV,以便将其导入Excel或Google表格。
Recurring_revenue.html.slim:
= link_to 'Download CSV', recurring_revenue_path(format: 'csv'), class: 'btn btn-success'
页面控制器:
@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
我在application.rb中添加了include "csv"
。任何人都可以看看,让我知道我做错了什么?