有以下jbuilder模板:
json.extract! @order do |order|
json.id order.id
json.room order.room
json.note order.note
json.order_status_id order.order_status_id
json.created_at order.created_at
json.restaurant_order_items order.restaurant_order_items
json.restaurant do
json.id order.restaurant.id
json.email order.restaurant.email
json.phone order.restaurant.phone
json.place do
json.title order.restaurant.place.title
end
end
end
我不明白为什么,但回应是"{}"。所以,我需要得到一个像"{ id: 10, ...}"这样的响应。我该怎么做?谢谢!
问题是extract!
旨在仅返回命名属性,它不使用给定的块。
json.extract!(@order, :id, :note)
# => {"id":1,"note":"test"}
除了调用 extract!
方法,还可以使用调用语法:
json.(@order, :id, :note)
# => {"id":1,"note":"test"}
考虑到这一点,您可以像这样开始创建模板:
json.(@order, :id, :note)
json.restaurant do
json.(@order.restaurant, :phone)
end
# => {"id":1,"note":"test","restaurant":{"phone":"123"}}
请注意,如果生成的 JSON 键的名称与对象上的属性相同,则无需提及两次。
json.(@order, :id)
# vs
json.id @order.id