Rails Jbuilder:如何将一个项目的数组格式化为JSON数组?

时间:2014-10-30 02:47:17

标签: ruby-on-rails json jbuilder

我正在尝试了解如何在类中内联使用Jbuilder方法。我想强制一个对象成一个长度为1的数组,以匹配预期的JSON规范。

以下是我想要的结果示例(请注意[]包装与sets相关联的值:

{
  "sets": [{
    "set_type": "default_set_type",
    "items": [
      {
        "item_id": "FFFF-0000-111",
        "quantity": "1"
      }
    ]
  }]
}

到目前为止,这是我的方法:

def to_3pl
  @shipment = self
  ...
  Jbuilder.new do |shipment|

    # How do I force jbuilder to wrap a single set with []?
    shipment.sets do
      shipment.set_type 'default_set_type'
      shipment.items @shipment.product_options do |product|
        shipment.item_id product.product_id.to_s
        shipment.quantity product.quantity.to_s
      end
    end
  end
end

这是我的方法生成的JSON(请注意,与sets关联的值未包含[]):

{
  "sets": {
    "set_type": "default_set_type",
    "items": [
      {
        "item_id": "FFFF-0000-111",
        "quantity": "1"
      }
    ]
  }
}

我查看了Jbuilder docs,我确信有办法解决这个问题,但我似乎无法弄明白。强制Jbuilder在类方法中用[]包装单个元素的语法是什么?

使用解决方案进行编辑

非常感谢@ dddd1919。这是一个已成功实现数组包装器的更新方法:

def to_3pl
  @shipment = self
  ...
  Jbuilder.new do |shipment|

    # Forces jbuilder to wrap the object with []
    shipment.sets Jbuilder.new.array!(['']) do |set|
      shipment.set_type 'default_set_type'
      shipment.items @shipment.product_options do |product|
        shipment.item_id product.product_id.to_s
        shipment.quantity product.quantity.to_s
      end
    end
  end
end

1 个答案:

答案 0 :(得分:3)

如果shipment.sets是一个列表,您可以使用Jbuilder#array!将数据序列化为json数组,如:

def to_3pl
  @shipment = self
  ...
  Jbuilder.new do |shipment|

    # How do I force jbuilder to wrap a single set with []?
    shipment.sets do
      Jbuilder.new.array!(shipment.sets) do |set|
        ....
      end
    end
  end
end