Displaying nested content


#1

Hi, I have two tables ‘item’ and ‘comment’ (comment belonging to item).
I am trying to list each item and the comments for that item within it.
For example:

Item One
Comment One
Comment Two
Comment Three

Item Two
Comment One
Comment Two

etc

I know I can place a loop within the loop to display the comments for
each item, but that seems inefficient. From what I have read, the
:include option in the controller can be used to carry out what I want,
but I am unsure of how to display this information within the view.

Controller

@items = Item.find(:all, :include => [:comments] )

View

<% for item in @items %>
<%=h item.title %>
<%=h item.body %>

(WOULD IT BE SOMETHING LIKE THIS?)
<% for comment in @items.comments %>
COMMENT GOES HERE
<% end %>

<% end %>

Any help would be greatly appreciated, thanks.


#2

Be brave, experiment!

Once you have an item, that item has comments, not the collection of
items (@items)

<% @items.each do |item| %>
<%=h item.title %>
<%=h item.body %>
<% item.comments.each do |comment| %>
<%=h comment.text (or whatever) %>
<% end %>
<% end %>