Understanding Eager Loading & How to use it? (specific issue)
Posted
by Elliot
on Stack Overflow
See other posts from Stack Overflow
or by Elliot
Published on 2010-05-19T12:13:32Z
Indexed on
2010/05/19
12:30 UTC
Read the original article
Hit count: 150
ruby-on-rails
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?
© Stack Overflow or respective owner