0

I have an array that merged from many sources. For example:

        list_items = []
        items.each do |item|
          # I convert details list to array by using to_a
          list_items.push(item.item_details.to_a)
        end

Then I use that custom array and serialize:

        {
            data: ActiveModel::Serializer::CollectionSerializer.new(
                list_items,
                serializer: ItemSerializer)
        }

Then I meet exception:

NoMethodError (undefined method `read_attribute_for_serialization' for Array:0x007fcee2290460)

If above code I don't use to_a but :

          list_items.push(item.item_details)

I will meet different exception:

undefined method `read_attribute_for_serialization' for Item::ActiveRecord_Associations_CollectionProxy:0x007fcee67ae

Please explain for me why I meet this exception and how to fix this.

Trần Kim Dự
  • 5,872
  • 12
  • 55
  • 107

2 Answers2

2

I have found answer for my problem. My problem because I insert an array to an array. Ruby will create two-dimensional array so my CollectionSerializer cannot work at this case. (because I assume that is one-dimensional array). So here is the fixing:

    list_items = []
    items.each do |item|
      # I convert details list to array by using to_a
      # list_items.push(*item.item_details.to_a)

      # using * operator before array for flattening array
      list_items.push(*item.item_details)
    end

After this, everything works like a charm.

    {
        data: ActiveModel::Serializer::CollectionSerializer.new(
            list_items,
            serializer: ItemSerializer)
    }

You can get more detail here: unary operator for array

Hope this help.

Community
  • 1
  • 1
Trần Kim Dự
  • 5,872
  • 12
  • 55
  • 107
0

I think this should work for you. try it out

{
 data: ActiveModel::ArraySerializer.new(list_items, each_serializer: ItemSerializer).to_json 
}
Narasimha Reddy - Geeker
  • 3,510
  • 2
  • 18
  • 23