使用JBuilder中创建的轨道嵌套JSON输出(Using JBuilder to create

2019-07-17 16:32发布

我在寻找如何创建使用JBuilder的嵌套JSON输出的例子。

我想创建和类似的输出:

{
    "name": "John Doe", 
    "reservations": [
        {
            "restaurant": "ABC",
            "reservation_time": "2012/12/01 20:00", 
            "details": {
                "address": "somewhere", 
                "rating": "5"
            }
        }, 
        {
            "restaurant": "CDE",
            "reservation_time": "2012/12/04 20:00", 
            "details": {
                "address": "somewhere else", 
                "rating": "3"
            }
        }
    ]
}

Answer 1:

解决了:

json.name user.name

json.array!(@reservations) do |json, reservation|
    json.restaurant reservation.restaurant.name
    json.reservation_time reservation.time

    json.details do 
        json.address reservation.restaurant.address 
        json.rating reservation.restaurant.rating 
    end
end 


文章来源: Using JBuilder to create nested JSON output in rails