jmccartie
jmccartie

Reputation: 4976

Active Model Serializers: Rendering array of values only renders first value

I have an array of values: [1, 2, 3, 4, 5]

I would like these to be rendered using json_api. I've successfully used ActiveModelSerializers::Model for other purposes to render a single plain Ruby object. But in this case, I have an array of objects. When rendered, AMS only renders the first object.

Setup

Model

class Step < ActiveModelSerializers::Model
  attr_accessor :value
end

Serializer

class StepSerializer < ActiveModel::Serializer
  attributes :value
end

Controller

class Api::StepsController < Api::BaseController

  def index
    steps = Option.pluck(:step).uniq.map { |v| Step.new(value: v) }
    render json: steps
  end

end

Output

{
  "data": [{
    "id": "step",
    "type": "step",
    "attributes": {
      "value": 1
    }
  }]
}

I would expect all 5 models to be rendered, but it appears only the first is being rendered. Any ideas?

Using active_model_serializers (0.10.7)

Upvotes: 2

Views: 819

Answers (1)

Alessandro De Simone
Alessandro De Simone

Reputation: 4215

I am sure you do not need this anymore, but maybe this can help someone.

I had a similar issue: in my case the issue was that I was using a resource with a id = nil. It generated only a single entry! Once I populated the id with unique identifier it worked as expected.

I realized that reading the json:api format (https://jsonapi.org/format/), since one of the requirement was:

Every resource object MUST contain an id member and a type member. The values of the id and type members MUST be strings.

I hope this can help

Upvotes: 2

Related Questions