View vs controller - data from multiple tables


#1

Hi all,

please pardon my question if it seems silly… I’m trying pretty hard to
learn though. :slight_smile:

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
Apples
Angels
Acrobats

Things that start with B
Books
Bottles
Bears

Things that start with C
Cats
Cars
Cocoons

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

Controller:

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

View:

<% for feed in @feeds %>

<%=h feed.name %>

<% for feeditem in feed.feed_items %> <%=h feeditem.name %> <% 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. :slight_smile:

Someone in IRC suggested, in the controller,

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

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.


#2

bplus wrote:

<% for feed in @feeds %>

<%=h feed.name %>

<% for feeditem in feed.feed_items %> <%=h feeditem.name %> <% end # end feeditem loop %>

<% end # end @feeds loop %>

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

Use eager loading (per
http://api.rubyonrails.com/classes/ActiveRecord/Base.html#M000715):

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

Then loop through @feed.feed_items in your view.

-B…