Reputation: 83
I'd like to build a JSON structure like so using JBuilder:
{
"name": "John Doe",
"reservations": [
{
"restaurant": "ABC",
"reservation_time": "2012/12/01 20:00",
"name": "John Doe"
},
{
"restaurant": "CDE",
"reservation_time": "2012/12/04 20:00",
"name": "John Doe"
}
]
}
{
"name": "Jane Doe",
"reservations": [
{
"restaurant": "Little Bites",
"reservation_time": "2012/12/01 20:00",
"name": "Jane Doe"
},
{
"restaurant": "Thai Taste",
"reservation_time": "2012/12/04 20:00",
"name": "Jane Doe"
}
]
}
I tried the solution here by ESoft, but I could not get it working. In his solution, it seems as if the "name" attribute is hard-coded?
What do I need to do in order to get JBuilder to generate the value of the name attribute from my data (my data is passed from my Rails controller to my .json.jbuilder file as an array)? (i.e. If John Doe has five reservations in my database, and Jack Daniels has 3 reservations, then I want my name attributes to be "John Doe" and "Jack Daniels").
Upvotes: 1
Views: 2236
Reputation:
You can use a block
with json.some_var_name
method to get named arrays (or any other results).
Lets say you have a user
with attributes name
(string) and reservations
(referenced models array). The full jbuilder template for your example could be:
json.array!(@users) do |user|
json.name user.name
json.reservations do
json.array!(user.reservations) do |reservation|
json.restaurant reservation.restaurant.name
json.reservation_time reservation.time
json.name user.name
end
end
end
Upvotes: 3