Skip to content

Cannot serialize without a root when sideloads are defined. #377

Closed
@mixonic

Description

@mixonic

Using this demo app: https://github.com/mixonic/ams-includes

matthewbeale:ams-includes be rails c
Loading development environment (Rails 4.0.0)
irb(main):001:0> c = Car.first
  Car Load (0.2ms)  SELECT "cars".* FROM "cars" ORDER BY "cars"."id" ASC LIMIT 1
=> #<Car id: 1, name: "audi">
irb(main):002:0> CarSerializer.new(c).to_json
  Wheel Load (2.5ms)  SELECT "wheels".* FROM "wheels" WHERE "wheels"."car_id" = ?  [["car_id", 1]]
  Car Load (0.3ms)  SELECT "cars".* FROM "cars" WHERE "cars"."id" = ? ORDER BY "cars"."id" ASC LIMIT 1  [["id", 1]]
  Wheel Load (0.2ms)  SELECT "wheels".* FROM "wheels" WHERE "wheels"."car_id" = ?  [["car_id", 1]]
  Car Load (0.1ms)  SELECT "cars".* FROM "cars" WHERE "cars"."id" = ? ORDER BY "cars"."id" ASC LIMIT 1  [["id", 1]]
=> "{\"wheels\":[{\"position\":\"back right\",\"car_id\":1},{\"position\":\"front left\",\"car_id\":1}],\"cars\":[{\"name\":\"audi\",\"wheel_ids\":[1,2]}],\"car\":{\"name\":\"audi\",\"wheel_ids\":[1,2]}}"
irb(main):003:0> CarSerializer.new(c).to_json(root: false)
ActiveModel::Serializer::IncludeError: Cannot serialize wheels when CarSerializer does not have a root!
... snip...

I'd like to propose an alternative: That sideloads are ignored when root is false or not present. This allows easy and clean implementation of #353, and for serializers to reference each other without the fear of blowing up.

I was surprised to see this not handled by AMS. Anyone else? I doubt I'm the first to raise this, but I couldn't find an issue targeting it specifically. Looking for feedback.

Metadata

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