Forum: Ruby on Rails view vs controller - data from multiple tables.

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
B04a5b554968d8d41001643e5be42e42?d=identicon&s=25 bplus (Guest)
on 2006-01-31 01:13
Hi all,

please pardon my question if it seems silly.. I'm trying pretty hard to
learn though. :)

I have 2 tables:

feeds (has_many feed_items)
feed_items (belongs_to feed)

Let's say Feeds has 3 feed.names:  "Things that Start with A", "Things
that start with B", "Things that start with C".

I want to print out, on one page, something like the following:

Things that start with A

Things that start with B

Things that start with C

I figured out how to do this in a loop in the view, i.e.


def index
   @feeds = Feed.find(:all)


<% for feed in @feeds %>
  <h3><%=h %></h3>
  <% for feeditem in feed.feed_items %>
    <%=h %>
  <% end # end feeditem loop %>

<% end # end @feeds loop %>

Is this bad style?  Should I be pulling this data somehow in the
controller instead?

I know it doesn't really matter for a simple example, but I plan to make
a fairly complex app (not insane, but a few dozen views by the time it's
done), and I'd like to do it correctly from the beginning. :)

Someone in IRC suggested, in the controller,

def index
  @feeds = Feed.find(:all)
  @feeditems = FeedItem.find(:all)

But then, of course, you get the entire list (A, B, and C) for each
feed.. so that's not quite right.

Any comments/suggestions appreciated.
39cf5e4fc67cd5d39ae60dab5dc335eb?d=identicon&s=25 Juicy (Guest)
on 2006-01-31 02:02
bplus wrote:
> <% for feed in @feeds %>
>   <h3><%=h %></h3>
>   <% for feeditem in feed.feed_items %>
>     <%=h %>
>   <% end # end feeditem loop %>
> <% end # end @feeds loop %>

> def index
>   @feeds = Feed.find(:all)
>   @feeditems = FeedItem.find(:all)
> end

Use eager loading (per

def index
  @feeds = Feed.find(:all, :include => :feed_items)

Then loop through @feed.feed_items in your view.

This topic is locked and can not be replied to.