简体   繁体   中英

Iterating over a hash response and saving to database

I have a hash response that looks like this.

{
    "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"
            }
        }
    ]
}

I will like to iterate over it and save selected values to the associated model. At the moment i can only iterate over a particular hash key like this after getting the response from the api.

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

What i want is to be able to iterate over the response hash and save a record whiles passing in values from other hash keys. For example;

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM