如果您的
@sophead.ods
是一个哈希的集合,可以很容易地实现它的合并
od
元素及其
od_items
:
json.ods @sophead.ods do |od|
json.od od.merge(od_items: od.od_items)
end
因为这些似乎是活动记录:
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