0
votes

In my application I have model Game which has has_many relation with model Stage, and model Stage which has has_many relation with model Winning.

I'm having problem with serializing, as I want to have a response looking like this:

{
  "game_id": 1,
  "stages": [
    {
      "stage_id": 1,
      "winnings": [
        {
          "winning_id": 1
        },
        { ... }
      ]
    },
    { ... }
  ]
}

However, when I serialize it like this:

class Admin::GameResultsSerializer < ActiveModel::Serializer
  attribute :id

  has_many :stages

  class StageSerializer < ActiveModel::Serializer
    attribute :id

    has_many :winnings

    class WinningSerializer < ActiveModel::Serializer
      attribute :id

      belongs_to :user
    end
  end
end

I does not return any winning in response - response only returns games with stages and I have no idea why.

Would appreciate help.

1
I'm not able to test this but perhaps adding has_many :winnings, through: :stages to your GameResultsSerializer would do the trick.Smek

1 Answers

0
votes

I managed to do it. The key was to include required tables in controller's render with include method:

class Admin::GameResultsController < Admin::BaseController
  def index
    render json: Game.find(params[:game_id],
           include: { stages: { winnings: :user } }  
  end
end

and it does the trick!