2013-11-03 50 views
0

我有一个观点文件photo_feed.html.erb,打印我需要使用以下内容:打印相关的映射数据

<% @photo_feed.each do |feed| %> 

<%= feed.id %> 
<%= feed.username %> 
<%= feed.photo_filename %> 
<%= feed.comments_count %> 
<%= feed.comments.map{|x| [x.username, x.comment]} %> 

<% end %> 

这样的作品,并在数组的数组输出评论为每张照片。

现在我的目标是使用jbuilder在json中输出这个数据,但我无法弄清楚如何打印数组。

JSON的输出应该是这个样子:

[{ “ID”:1, “用户名”: “鲍勃”, “photo_filename”: “img.jpg”, “comments_count”:2, [[“用户名”:“泰德”,“评论”:“你好, 特德,你 朋克。”] [“用户名”:“卡尔”,“评论”:“愤怒。”]]},{“ :2,“username”:“lisa”,“photo_filename”:“img2.jpg”,“comments_count”:1,[[“username”:“roger”,“comment”:“Blah。”]]}

所以我的问题:你如何在json.jbuilder文件中打印关联的映射数据?

+0

这是你需要什么? http://stackoverflow.com/questions/10137259/how-could-i-render-to-a-string-a-json-representation-of-a-jbuilder-view/10234259?noredirect=1#comment22210287_10234259 –

回答

0

应该是这样的:

json.array!(@photo_feed) do |feed| 
    json.extract! feed, :id, :username, :photo_filename, :comments_count 
    json.comments feed.comments do |json, comment| 
    json.(comment, :username, :comment) 
    end 
end 

看看这个railscast - http://railscasts.com/episodes/320-jbuilder