自定义输出轨道json api with:include

时间:2016-05-25 17:32:42

标签: ruby-on-rails json api-design

现在我有我的api渲染这个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"
                                          }
                                        ]
                            }]

   }
]

我使用Rails的render:json帮助器渲染它。像这样:

@calendar = Journey.all

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

然而,前端开发人员(他通过Angular消费API)问我改变了JSON的结构,他需要团队与匹配处于同一级别。有点像这样:

[
       {
              "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",

                            }]

   }
]

正如你可以看到比赛,球队现在合并了。

我怎样才能做到这一点?

干杯!

1 个答案:

答案 0 :(得分:0)

我刚刚用alphabets

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

teams是您给定的哈希

  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 }} 
                              }