简体   繁体   中英

How to serialize an array of hash

I have a controller thats building an array of hash as follows:

product_controller.rb

    class ProductController < ApplicationController

    def product
      existing_products = Product.where(abc, deb)

      existing_products = mapped_existing_products(existing_products)

      some_other_method(existing_products)

      render status: :ok,
             json: { existingProducts: existing_products }

    end

    private

    def mapped_existing_products(existing_products)
    product_mapping = []
    existing_products.each do |product|
      product_mapping << {
        product_id: product.id,
        order_id: activity.product_order_id
      }
    end
    product_mapping
  end
end

I am new to ruby but from what i read i have to create a serializer but serializer is for model and i dont have serializer for Product since i am rendering a hash with new attributes.

I tried to create a serializer like below

class ProductMappingSerializer < ActiveModel::Serializer
  attributes :product_id, :order_id
end

and in controller

render json: existing_products,
           serializer: ProductMappingSerializer,
           status: :ok

end

but when i test it i get error

undefined method `read_attribute_for_serialization' for #<Array:0x00007fa28d44dd60>

How can i serialize attributes of hash in rendered json?

Outside of Rails, one way to serialize a Ruby object is with Marshal

# make array of hash
irb> a_of_h = [{}, {:a => 'a'}]
=> [{}, {:a=>"a"}]

# serialize it
irb> dump = Marshal.dump(a_of_h)
=> "\x04\b[\a{\x00{\x06:\x06aI\"\x06a\x06:\x06ET"

# bring it back
irb> back = Marshal.load(dump)
=> [{}, {:a=>"a"}]

# check that it happened
irb> back
=> [{}, {:a=>"a"}]

This may or may not meet the needs of your application.

Another way is with JSON

irb> require 'json'
=> true
irb> j = JSON.dump(a_of_h)
=> "[{},{\"a\":\"a\"}]"

There is also YAML

irb> require 'yaml'
=> true
irb> YAML.dump(a_of_h)
=> "---\n- {}\n- :a: a\n"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM