2016-04-30 30 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

。 '創造されたもの'とは何ですか?それは列かメソッドか – tadman

+0

'created'はストライプのjson unixタイムスタンプです:' "created":1462001409、 ' – Sylar

+0

タイムスタンプの合計はなぜですか?それは私には意味がありません。日付として必要な場合は、 'Time.at(timestamp)'が変換されます。 – tadman

答えて

2

あなたは量と各料金で解析された日付を格納し、ストライプ内の各電荷オブジェクトを反復処理する必要があります:あなたはおそらくここに代わりmap` `のeach``使用する必要があります

# 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

これはまあまあまあまあですが、いくつかのことがあります: 'charged_by_date'は、デフォルト値0を望むなら' Hash.new(0) 'になり、後で' || = 'テストを避けます。 'Date.strptime'は、仕事を簡潔にする' Time.at'よりもやや厄介です。 – tadman

+0

私はこれを後で実行します。ありがとう – Sylar

+0

@tadman 'Hash.new(0)'について知りませんでした、ありがとう。 –

関連する問題