问题
I have a list of shows in a database that need to be output in a certain JSON style in order to work with Polymaps.
Part of this includes the need to iterate over one section in order to create a list of points. I'm pretty certain that this needs to be achieved using :include in the render :json => @results bit of the code.
Here's the code as it stands:
def gigs
@gigs = Show.where(:displayname => "Vans Warped Tour 2011")
@giggage = [{
:type => "FeatureCollection",
:features => [
@gigs.each do |gig|
:type => "feature",
:geometry => {
:coordinates => [
gig['lng'],
gig['lat']
],
:type => "Point"
},
:properties => gig
end
]
}]
render :json => @giggage
end
There's an each loop inside a hash which I know you can't do, but that's the best way to illustrate what I'm going for, I'm going in circles on this.
I did try this which got me some of the way there, but only returned the one result because of the structure of the loop:
def gigs
@gigs = Show.where(:displayname => "Vans Warped Tour 2011")
@gigs.each do |gig|
@gigs_to_render = {
:type => "FeatureCollection",
:features => [
:type => "feature",
:geometry => {
:coordinates => [
gig['lng'],
gig['lat']
],
:type => "Point"
},
:properties => gig
]
}
end
render :json => @gigs_to_render
end
Thanks for your help! Anyone. Everyone!
回答1:
The code as it stands should be very close to working. Just change each
to map
and surround the body of the block in curlies so it all gets returned as a hash for each gig.
来源:https://stackoverflow.com/questions/6513627/rewrite-json-structure-and-include-an-each-loop-in-rails