active_model_serializers: belongs_to and has_one Nested Form Use Wrong Serializer

Hi, I have a problem with nested serializer. This is my serializers

class FormulaSerializer < ActiveModel::Serializer

  belongs_to :author
  has_many :steps
  has_many :cook_ingredients
  has_many :stock_locations

end

class CookIngredientSerializer < ActiveModel::Serializer
  has_one :ingredient, each_serializer: IngredientSerializer
  has_one :unit

  attributes :description, :quantity, :ingredient, :unit
end

class IngredientSerializer < ActiveModel::Serializer
  attributes :id, :name

  has_many :products
end

My formulas API result. Actual result:

{
  "formulas":
  [{
    "steps": , // some data
    "cook_ingredients": [
    {
      "ingredient": {
        "id": 3,
        "name": "bawang",
        "created_at": "2015-08-05T06:27:20.065Z",
        "updated_at": "2015-08-26T06:53:16.874Z",
        "taxon_id": null
      }
    }
    ],
    "stock_locations": [
    {
      "id": 2,
    }]
  }]
}

Why there is created_at, updated_at, and taxon_id is there? It seem that it rendered without using my serializer.

Expected result

{
  "formulas":
  [{
    "steps": , // some data
    "cook_ingredients": [
    {
      "ingredient": {
        "id": 3,
        "name": "bawang",
        "products": [] // some products
      }
    }
    ],
    "stock_locations": [
    {
      "id": 2,
    }]
  }]
}

The serializers works perfectly if I render the Ingredient API. Is this a bug?

About this issue

  • Original URL
  • State: closed
  • Created 9 years ago
  • Comments: 22 (20 by maintainers)

Most upvoted comments

By design, only the first level associations are serialized (this is being discussed currently). In your case, you could add include: '**' in your render call so that all associations will be serialized recursively.