Question

I have a view file photo_feed.html.erb that prints what I need using the following:

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

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

<% end %>

That works, and outputs the comments in an array of arrays for each photo.

Now my goal is to output this in json using jbuilder, and I can't figure out how to print the array.

The json output should look something like:

[{"id":1,"username":"bob","photo_filename":"img.jpg","comments_count":2,[["username":"ted","comment":"Hello ted, you punk."]["username":"carl","comment":"Angry."]]},{"id":2,"username":"lisa","photo_filename":"img2.jpg","comments_count":1,[["username":"roger","comment":"Blah."]]}

So my question: how do you print associated mapped data in json.jbuilder files?

Was it helpful?

Solution

Should be something like:

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

Check out this railscast - http://railscasts.com/episodes/320-jbuilder

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top