2016-04-30 49 views
1

我正在遍历stripe charge object,我想总计每天的总计amount如果条形码中的收费日期相同,所有金额的总和

# Returns an array object of charges for a customer 
@customer_charges = Stripe::Charge.all(:customer => current_user.stripeid) 

浏览:

<% @customer_charges.map do |c| %> 
    On Monday, you were charged a total of <%= c.amount %> 
<% end %> 

当然上面做无非是每个收费输出线以上,但不是当天的总和。我面临的困难是总结每一天的所有费用。有人能指出我正确的方向吗?

输出会是这样:

"On Monday, you were charged a total of 200000" 
"On Tueesday, you were charged a total of 500000" 
etc... 

相反的:

On Monday, you were charged a total of 100000" 
On Monday, you were charged a total of 100000" 
etc... 

view看起来杂乱无章与if statements线比较日期,并且看起来不正确的。

+0

你或许应该使用'这里,而不是'map' each'。什么是“创造”?那是一列还是一种方法 – tadman

+0

好的。 'created'是条纹的json unix timestamp:''created“:1462001409,' – Sylar

+0

你为什么总计时间戳?这对我来说毫无意义。如果你需要它们作为日期,'Time.at(timestamp)'将会转换。 – tadman

回答

2

你需要通过条纹每次充电对象上进行迭代,存储量和每个负责解析日期:

# Fetch charges in batches of 100 records from Stripe API, yield each individual charge to a block. 
def each_stripe_charge_for_customer(customer_id) 
    starting_after = nil 
    loop do 
    customer_charges = Stripe::Charge.all(customer: customer_id, limit: 100, starting_after: starting_after) 
    break if customer_charges.none? 
    charges.each do |charge| 
     yield charge 
    end 
    starting_after = charges.data.last.id 
    end 
end 

charges_by_date = Hash.new(0) 

# For each Stripe charge, store the date and amount into a hash. 
each_stripe_charge_for_customer(current_user.stripeid) do |stripe_charge| 
    # Parses Stripe's timestamp to a Ruby date object. `to_date` converts a DateTime object to a date (daily resolution). 
    charge_date = Time.at(stripe_charge.created).to_date 
    charge_amount = stripe_charge.amount 

    charges_by_date[charge_date] += charge_amount 
end 
+0

这是相当不错的,但有几件事:如果您希望默认值为0,则'charges_by_date'可以是'Hash.new(0)',这样可以避免稍后使用'|| ='测试。 “Date.strptime”比简单地完成工作的Time.at文件要笨得多。 – tadman

+0

我会稍后再去。谢谢 – Sylar

+0

@tadman不知道'Hash.new(0)',谢谢。 –