开发者

Understanding Eager Loading & How to use it? (specific issue)

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(:includ开发者_开发知识库e => [: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?


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜