jeudi 13 août 2015

Rails 4.Combine 2 arrays

I have 2 arrays and i want to combine them in one which have to return nested JSON. The first one is cleaner which returns

{
  "response": [
    {
      "id": 1,
      "first_name": "Fernando",
      "last_name": "Gomez",
      "avg_rating": "4.5"
    }  
  ]
}

The second one is reviews from the clients which return the name of the client,comment and rating:

{
  "response": [
    {
      "id": 1,
      "score": 4,
      "comment": "Comment",
      "first_name": "John Doe"
    }
  ]
}

So i try to zip them and loop over each of them here is my code:

cleaners.zip(reviews).each do |cleaner, review|
  if cleaner.id == review.id
   test['first_name'] = cleaner.first_name
   test['last_name'] = cleaner.last_name
   test['rating'] = review.score
   test['comment'] = review.comment
   test['client_name'] = review.first_name
  end
end

When i return my result is:

{
  "response": {
    "first_name": "Fernando",
    "last_name": "Gomez",
    "rating": 4,
    "comment": "Comment",
    "client_name": "John Doe"
  }
}

But my result have to be nested cuz some of the cleaners will have many reviews.It have to be something like this:

{
  "response": {
    "first_name": "Fernando",
    "last_name": "Gomez",
    "score_from_client": [
                {
                  "rating": 4,
                  "comment": "Comment",
                 "client_name": "John Doe"
                }
                ]
  }
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire