2016-05-25 8 views
0

は今、私は私のAPIが、私はレンダリングを使用して、これをレンダリングしていますカスタム出力レールJSON APIとは:RailsのJSONのヘルパー:

[ 
     { 
       "id": 1, 
       "name": "1", 
       "matches": [{ 
          "score_a": 1, 
          "score_b": 3, 
          "time": "2016-05-20T15:00:00.000Z", 
          "teams": [ 
             { 
              "name": "Team 1", 
              "logo_url":"test.jpg" 
              }, 
             { 
              "name": "Team 2", 
              "logo_url": "test.2jpg" 
              } 
             ] 
          }] 

    } 
] 

このJSONをレンダリングする必要があります。フロントエンドの開発者が(彼は角度を通じてAPIを消費している)の変化にJSONの構造を私に求めている

@calendar = Journey.all 

render json: @calendar, include: { matches: 
            { include: { teams: { } }} 
            }    

どのようにこれまでに、彼はチームが試合と同じレベルにする必要があります。このような。

[ 
     { 
       "id": 1, 
       "name": "1", 
       "matches": [{ 
          "score_a": 1, 
          "score_b": 3, 
          "time": "2016-05-20T15:00:00.000Z", 
          "team_a_name": "Team 1", 
          "team_a_logo_url":"test.jpg", 
          "team_b_name": "Team 2", 
          "team_b_logo_url": "test.2jpg", 

          }] 

    } 
] 

このように、チームは現在マージされています。

どうすればこの問題を解決できますか?

乾杯!

答えて

0

私はちょうどdigits

teams = [ 
      { 
       "name": "Team 1", 
       "logo_url":"test.jpg" 
      }, 
      { 
       "name": "Team 2", 
       "logo_url": "test.2jpg" 
      } 
      ] 

teamsであるあなたの与えられたハッシュとalphabetsを置き換え

array = [] 

    teams.count.times {|i| 
     teams[i].keys.each do |k,v| 
      key = "team_"+ (i+1).to_s + "_"+k.to_s 
      array.push(key) 
     end 
    } 

    #=> ["team_1_name", "team_1_logo_url", "team_2_name", "team_2_logo_url"] 

今、私たちは自分の価値観

value_array = [] 

teams.each do |k| 
    k.each do |key, val| 
     value_array.push(val) 
    end 
end 

#=> ["Team 1", "test.jpg", "Team 2", "test.2jpg"] 

今、私たちは結合しようとしているため、配列を作成します。両方の配列

new_teams = Hash[*array.zip(value_array).flatten] 
#=> {"team_1_name"=>"Team 1", "team_1_logo_url"=>"test.jpg", "team_2_name"=>"Team 2", "team_2_logo_url"=>"test.2jpg"} 

今あなたがJSONでnew_teams

render json: @calendar, include: { matches: 
           { include: { teams: new_teams }} 
           } 
を割り当てることができます