Hakeem Baba
Hakeem Baba

Reputation: 707

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])

Upvotes: 0

Views: 55

Answers (1)

max pleaner
max pleaner

Reputation: 26758

You can just use response["competition"]["id"]

Upvotes: 1

Related Questions