如何使用Jbuilder显示父信息,子信息嵌套在下面

How to use Jbuilder to display parent info with child information nested underneath

我在 rails 中使用 jbuilder 在 rails 应用程序中生成一些 JSON。 在我的模型中,'od_items' 属于 'od','ods' 属于 'sophead'。

我想显示'sophead'的每个'od',然后嵌套在每个'od'下面,我想显示属于[=27]的每个'od_items' =].

到目前为止,这是我的代码:

json.ods @sophead.ods do |od|
  json.od od
  json.od_items od.od_items do |od_item|
    json.od_item od_item
  end
end

这是输出以下内容JSON:

ods: [
{
od: {
id: 51,
sophead_id: 386,
created_at: "2018-03-21T15:28:48.802Z",
updated_at: "2018-03-21T15:28:48.802Z",
status: "Open"
},
od_items: [
{
od_item: {
id: 285,
od_id: 51,
qty: "1.0",
part: "CARRIAGE CHARGE",
description: "Simpson Carriage Charge",
created_at: "2018-03-21T15:28:48.823Z",
updated_at: "2018-03-21T15:28:48.823Z"
}
},
{
od_item: {
id: 284,
od_id: 51,
qty: "1.0",
part: "MISCELLANEOUS",
description: "Split Box Charge",
created_at: "2018-03-21T15:28:48.816Z",
updated_at: "2018-03-21T15:28:48.816Z"
}
}
]
}
],

问题是我希望 'od_items' 嵌套在它相关的 'od' 中,而不是出现在它旁边。

这应该很容易整理,但我在网上找不到任何东西。

(关于 Stack overflow 的第一个问题 - 非常感谢)

如果您的 @sophead.ods 是一个散列集合,您可以轻松实现它,将 od 元素与其 od_items 元素合并:

json.ods @sophead.ods do |od|
  json.od od.merge(od_items: od.od_items)
end

因为这些似乎是 ActiveRecords:

json.ods @sophead.ods do |od|
  json.od od.as_json.merge(od_items: od.od_items.map(&:as_json))
end

根据 README,获得相同结果的另一种方法是使用 json.merge!:

json.ods @sophead.ods do |od|
  json.od do
    json.id od.id
    json.sophead_id od.sophead_id
    json.created_at od.created_at
    json.updated_at od.updated_at
    json.status od.status
    json.merge! { od_items: od.od_items.as_json}
end

另一种确保更好性能的方法是使用 ActiveModelSerializer

class OdSerializer < ActiveModelSerializers::Model
  attributes :id, :sophead_id, :created_at, :updated_at, :status
  has_many :od_items, serializer: OdItemSerializer
end

class OdItemSerializer < ActiveModelSerializers::Model
  attributes :id, :od_id, :qty, :part, :description, :created_at, :updated_at
end

# And in the controller
render json: @sophead.ods, each_serializer: OdSerializer