Skip to content

Include does not work on nested associations #1194

Closed
@givigier

Description

I'm trying to use the feature of nested associations. My structure of serializers is:

class V1::QuotesController < ApplicationController
  def show
    render json: @quote, serializer: V1::QuoteSerializer, include: { company: [:addresses, :phones] }
  end
end
class V1::QuoteSerializer < ActiveModel::Serializer
  attributes :id
  has_one :company, serializer: V1::CompanySerializer
end
class V1::CompanySerializer < ActiveModel::Serializer
  attributes :id
  has_many :phones, serializer: V1::PhoneSerializer
  has_many :addresses, serializer: V1::AddressSerializer
end
class V1::AddressSerializer < ActiveModel::Serializer
  attributes :city
end
class V1::PhoneSerializer < ActiveModel::Serializer
  attributes :number
end

When I add 'include' of associations on controller(like on QuotesController) it works fine and return:
{"id"=>"1", "company"=>{"id"=>"1", "addresses"=>[], "phones"=>[]}}

Otherwise, when I add 'include' of associations on serializer it does not work and doesn't return addresses and phones.

class V1::QuotesController < ApplicationController
  def show
    render json: @quote, serializer: V1::QuoteSerializer
  end
end
class V1::QuoteSerializer < ActiveModel::Serializer
  has_one :company, serializer: V1::CompanySerializer, include: [:addresses, :phones]
end

{"id"=>"1", "company"=>{"id"=>"1"}}

I was reading the docs and apparently it should work on serializer too.

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions