Am I hitting the database twice?

Hi --

Controller:
@books.collect { |book| book.authors }

View:
<td>
<% for author in book.authors %>
   <%= h author.name %>
<% end %>
</td>

When I comment out the controller line I get the same result. So should
I let the view hit the database on its own or is there some benefit to
doing it in the controller? Code in the view cannot be refactored in
either situation.

The controller line appears to discard its result, so I'm not
surprised that commenting it out makes no difference :slight_smile:

Assuming that there's a line like this in the controller:

   @books = Book.find(:all)

and like this in the view:

   <% @books each do |book| %> # or an equivalent for loop

you could change the controller line to:

   @books = Book.find(:all, :include => "authors")

which would pre-load all the author records into the @books collection
and save some database hits later on.

David