首页 > 解决方案 > 如何序列化哈希数组

问题描述

我有一个控制器,它正在构建一个哈希数组,如下所示:

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

我是 ruby​​ 的新手,但从我读到的内容来看,我必须创建一个序列化程序,但序列化程序是用于模型的,我没有用于 Product 的序列化程序,因为我正在渲染具有新属性的哈希。

我试图创建一个如下所示的序列化程序

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

并在控制器中

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

结尾

但是当我测试它时我得到错误

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

如何在呈现的 json 中序列化哈希的属性?

标签: ruby-on-railsruby

解决方案


在 Rails 之外,序列化 Ruby 对象的一种方法是使用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"}]

这可能会也可能不会满足您的应用程序的需求。

另一种方法是使用JSON

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

还有YAML

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

推荐阅读