Search code examples
ruby-on-railsarraysactive-model-serializers

Rails: how to use CollectionSerializer for custom array


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.


Solution

  • 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.