重写 JSON 结构并在 Rails 中包含 EACH 循环
我在数据库中有一个节目列表,需要以某种 JSON 样式输出才能使用 Polymaps。
其中一部分包括需要迭代一个部分以创建点列表。我非常确定这需要在渲染中使用 :include 来实现:json => @results 代码的一部分。
这是现在的代码:
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
散列中有一个每个循环,我知道你不能这样做,但这是说明我要做什么的最好方法,我会在这个问题上绕圈子。
我确实尝试过这个,这让我得到了一些帮助,但由于循环的结构,只返回了一个结果:
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
结束
感谢您的帮助!任何人。每个人!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
目前的代码应该非常接近工作。只需将
each
更改为map
并用花括号包围块的主体,这样它就可以作为每个演出的哈希值返回。The code as it stands should be very close to working. Just change
each
tomap
and surround the body of the block in curlies so it all gets returned as a hash for each gig.