0

JSONベースのAPIの結果のレンダリングに取り組んでおり、結果を適切に反復する方法に苦労しています。私のAPI呼び出しの要点:

@invoice = ActiveSupport::JSON.decode(api_response.to_json)

結果のハッシュ配列は次のとおりです。

{
"amount_due"=>4900, "attempt_count"=>0, "attempted"=>true, "closed"=>true, 
"currency"=>"usd", "date"=>1350514040, "discount"=>nil, "ending_balance"=>0, "livemode"=>false, 
"next_payment_attempt"=>nil, "object"=>"invoice", "paid"=>true, "period_end"=>1350514040, "period_start"=>1350514040, "starting_balance"=>0, 
"subtotal"=>4900, "total"=>4900, 
"lines"=>{
    "invoiceitems"=>[], 
    "prorations"=>[], 
    "subscriptions"=>[
        {"quantity"=>1, 
            "period"=>{"end"=>1353192440, "start"=>1350514040}, 
            "plan"=>{"id"=>"2", "interval"=>"month", "trial_period_days"=>nil, "currency"=>"usd", "amount"=>4900, "name"=>"Basic"}, 
            "amount"=>4900}
    ]
}}

レンダリングして請求するために、すべての「行」をループして表示しようとしています。各「行」には、0個または多数の「請求書」、「按分」、および「サブスクリプション」を含めることができます。

私はここまで到達しましたが、ネストのいずれかを使用して対処する方法を理解できません。

<% @invoice["lines"].each_with_index do |line, index| %>

# not sure what the syntax is here ?

<% end %>

私は現在ビューで作業していますが、並べ替えたら、このほとんどをヘルパーに移動します。

ありがとう!

4

1 に答える 1

1

添付したハッシュの例に基づくと、配列のように@invoice ["lines"]でオブジェクトを列挙しようとしているため、問題が発生していると思われます。これに伴う問題は、オブジェクトがハッシュであるため、列挙が少し異なる方法で処理されることです。

キーのinvoiceitemssubscriptions、およびprorationsは常に返され、これらのカテゴリはそれぞれ異なる属性を持つため、生成された請求書ではおそらく異なって見えるという仮定に基づいているため、3つの値に対して3つの別々のループが必要です。ハッシュ。これがどのように機能するかの例を以下にコーディングしました。

<% @invoice["lines"]["invoiceitems"].each_with_index do |item, index| %>
  # display logic of an invoice item
<% end %>

<% @invoice["lines"]["prorations"].each_with_index do |proration, index| %>
  # display logic of a proration
<% end %>

<table>
  <tr>
    <th>#</th>
    <th>Quantity</th>
    <th>Start Period</th>
    <th>Amount</th>
  </tr>
  <% @invoice["lines"]["subscriptions"].each_with_index do |subscription, index| %>
  <tr>
    # display logic of a subscription
    <td><%= index %></td>
    <td><%= subscription["quantity"] %></td>
    <td>
      <%= DateTime.strptime("#{subscription["period"]["start"]}",'%s').strftime("%m/%d/%Y") %>
    </td>
  </tr>
  <% end %>
</table>

サブスクリプションのすべてのフィールドを実行したわけではありませんが、これは続行するための十分な例になるはずです。

于 2012-10-19T02:28:57.060 に答える