使用 :include 的自定义输出 rails json api

Custom Output rails json api with :include

现在我有 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: { } }} 
                                  }            

但是,前端开发人员(他正在使用 API 到 Angular)要求我更改 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",

                            }]

   }
]

如您所见,比赛和队伍现在合并了。

我怎样才能做到这一点?

干杯!

我刚刚将 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 }} 
                              }