Closed burtondav closed 11 years ago
What json do you want to get?
I'm trying to get json for an ancestry gem table. The table contains a tree of location data. Because it's a tree, I only need to start with the first record - then I access their children. This is the code I'm trying:
json.locations do
json.label @location.name
json.children @location.children do |child|
json.label child.name
json.children child.children do |child2|
json.label child2.name
json.children child2.children do |child3|
json.label child3.name
end
end
end
end
The results start with a { and jqTree requires that it start with a [
This is what I'm getting:
BTW - If I use the following, the output starts with [
But, this produces the wrong data.
json.array!(@locations) do |location|
json.label location.name
json.children location.children do |child|
json.label child.name
json.children child.children do |child2|
json.label child2.name
json.children child2.children do |child3|
json.label child3.name
end
end
end
end
First, I might want to use a partial for this instead of having a child2, child3, etc. Unless you only always have three levels. Maybe something like
_your_partial.json.jbuilder:
json.label location.name
json.children do
json.array! location.children do |child|
json.partial! 'your_partial', :location => child
end
end
In order to get an array at the top level, in your controller, put @location inside of an array (i.e. @locations = [@location]
). Then your view would look like:
json.locations do
json.array! @locations do |location|
json.partial! 'your_partial', :location => location
end
end
My controller was like this (I only need the first location to start the tree):
def tree
@location = Location.find(1)
end
I tried this - but, got errors.
def tree
@location = [Location.find(1)]
end
I tried this:
json.locations do
json.label @location.name
json.children @location.children do |child|
...
But, it still starts with { instead of [
You should use array!
to get an array.
You could do:
json.array! [1] do json.location do ... end end
Sent from my iPhone
On Feb 27, 2013, at 12:17 PM, David Burton notifications@github.com wrote:
I tried this:
json.locations do json.label @location.name json.children @location.children do |child| ... But, it still starts with { instead of [
— Reply to this email directly or view it on GitHub.
jqTree requires the json data to start with [ not {
I can do that with jbuilder when building an array! - but, is there a way to modify this code:
json.locations do json.lavel @location.name end