views:

25

answers:

1

I have the following relation in my rails app:

genre - has many - authors

authors - belong to genre and has many books

books - belongs to authors and belongs to users

(users can add books to the db)

in my controller I have:

@books=current_user.books(:include => [:author => :genre], :order => 'books.created_at DESC')---

--

In my controller I used to have:

@authors = Author.All @genres = Genre.All

etc.

--

In my view I have

@genres.each do |genre|

@authors.each do |author|

if author.genre_id == genre.id 

    stuff

end

end

end

Now that I'm using eager loading, I can't imagine this is the best way to do this (nor does it work as I don't have the @ variables) - I was wondering if anyone could shed some light on how to approach this?

A: 

Eager loading simply means that when you load a book it will immediately fetch the related object. So for example when you do:

<% @books.each do |book| %>
     <%= book.author.name %>
<% end %>

book.author.name won't hit database again because it was already loaded when the book was fetched.

Your problem is that you are missing the complete list of Authors and Genres - and this is not related to eager loading.

I don't see any other way than to load it as you did before (i.e. @authors = Authors.all).

Slobodan Kovacevic
Thanks for the info!
Elliot