Rails结构到JSON对象



我已经创建了一个基于简单结构的自定义类,我需要用JSON:将其取回

    class ItemTag <
      Struct.new(:id, :item_id, :type, :subtype, :top, :left, :height, :width, :name, :alternate, :photo_url, :price, :quantity, :comment, :memo)
      def to_map
        map = Hash.new
        self.members.each { |m| map[m] = self[m] }
        map
      end
      def to_json(*a)
        to_map.to_json(*a)
      end
    end

在我的控制器中,我收集这样的数据:

@tags = design.item_links.all.map{ |pi| ItemTag.new(pi.id,pi.item_id,pi.item.type,pi.item.subtype,pi.top,pi.left,pi.height,pi.width,pi.item.name,pi.item.alternate_name,pi.item.logo_photo(:thumb),pi.price,pi.quantity,pi.public_note,pi.private_note)}

最后,在我看来,我需要将这些数据作为json字符串传递到javascript函数中,所以我这样做了:

<%= raw(@tags.to_json) %>

我得到的输出看起来是这样的:

[["1b245b45","444dc0e6","plant","cactus",94,661,110,174,"Blue mistflower","conoclinium coelestinum"," ",56.0,4,"test","test"],["21e8db0c","3097c392","plant","bamboo",128,108,161,100,"Green and gold","chrysogonum virginianum"," ",76.0,5,"this is very green","dont tell them it has gold"]]

如果我把to_json放在控制器中的映射操作中,它会为每个记录生成有效的json,但它不会以json的形式给我所有对象的数组。

有什么想法吗?

我认为这可能有效:

def as_json(*a)
  to_map
end

ruby中的as_json方法类似于JavaScript中的to_json函数。它返回准备序列化的数据,而不是序列化的数据。

最新更新