Skip to content

Rails 5, ActiveRecord has_many for nested Serializers not used? #2011

Open
@tdegrunt

Description

@tdegrunt

Probably doing something wrong, but ...

Expected behavior vs actual behavior

Given the following models & serialisers:

class Shipment < ApplicationRecord
    has_many :shipment_service_types
end
class ShipmentServiceType < ApplicationRecord
    belongs_to :shipment
    has_many :time_windows
end
class TimeWindow < ApplicationRecord
    belongs_to :shipment_service_type
end

# serializers
class ShipmentSerializer < ActiveModel::Serializer
  attributes :id, :name
  has_many :shipment_service_types, serializer: ShipmentServiceTypeSerializer
end
class ShipmentServiceTypeSerializer < ActiveModel::Serializer
  attributes :name
  has_many :time_windows, serializer: TimeWindowSerializer
end

class TimeWindowSerializer < ActiveModel::Serializer
  attributes :id, :start, :end
end

The output I expect to see is:

{
  "shipment": {
    "id": 1,
    "name": "Test",
    "shipment_service_types": [
      {
        "id": 1,
        "name": "test",
        "time_windows": [
          {
            "id": 1,
            "start": "2000-01-01 09:05:41 UTC",
            "end": "2000-01-01 10:05:41 UTC"
          }
        ]
      }
    ]
  }
}

What I'm getting is:

{
  "shipment": {
    "id": 1,
    "name": "Test",
    "shipment_service_types": [
      {
        "id": 1,
        "name": "test"
      }
    ]
  }
}

Steps to reproduce

(e.g., detailed walkthrough, runnable script, example application)

I've made an example app: https://github.com/tdegrunt/ams_test

Environment

ActiveModelSerializers Version (commit ref if not on tag):

Output of ruby -e "puts RUBY_DESCRIPTION":
ruby 2.2.4p230 (2015-12-16 revision 53155) [x86_64-darwin15]

OS Type & Version:
macOS 10.12.2

Integrated application and version (e.g., Rails, Grape, etc):
Rails 5.0.1

Backtrace

(e.g., provide any applicable backtraces from your application)

Additonal helpful information

(e.g., Gemfile.lock, configurations, PR containing a failing test, git bisect results)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions