Forum: Ruby on Rails Displaying nested content

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Dan S. (Guest)
on 2009-01-14 15:46
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.
Ar C. (Guest)
on 2009-01-14 20:53
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 %>
This topic is locked and can not be replied to.