【问题标题】:Iterating over a hash response and saving to database迭代哈希响应并保存到数据库
【发布时间】:2020-12-17 21:19:24
【问题描述】:

我有一个看起来像这样的哈希响应。

{
    "count": 1,
    "filters": {
        "status": [
            "FINISHED"
        ]
    },
    "competition": {
        "id": 2015,
        "name": "Ligue 1",
    },
    "matches": [
        {
            "id": 296861,
            "score": {
                "winner": "HOME_TEAM",
                "fullTime": {
                    "homeTeam": 4,
                    "awayTeam": 1
                },
            "homeTeam": {
                "id": 523,
                "name": "Olympique Lyonnais"
            },
            "awayTeam": {
                "id": 528,
                "name": "Dijon Football Côte d'Or"
            }
        }
    ]
}

我想对其进行迭代并将选定的值保存到关联的模型中。 目前,我只能在从 api 获得响应后迭代这样的特定哈希键。

match_array = response["matches"]
match_array.each do | value |
  MatchScore.create(winner: value["score"]["winner"])
end

我想要的是能够迭代响应哈希并保存记录,同时从其他哈希键传递值。例如;

MatchScore.create(winner: value["score"]["winner"], competition_id: competition[:id])

【问题讨论】:

  • 你能用response["competition"]["id"]吗?
  • 啊,那行得通。谢谢

标签: ruby-on-rails json ruby hash


【解决方案1】:

你可以使用response["competition"]["id"]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-17
    • 1970-01-01
    • 2011-02-28
    • 2014-12-15
    • 1970-01-01
    • 2011-10-05
    • 1970-01-01
    相关资源
    最近更新 更多