Help me understand Rails eager loading

Posted by aaronrussell on Stack Overflow See other posts from Stack Overflow or by aaronrussell
Published on 2010-05-14T15:02:00Z Indexed on 2010/05/14 15:04 UTC
Read the original article Hit count: 278

I'm a little confused as to the mechanics of eager loading in active record. Lets say a Book model has many Pages and I fetch a book using this query:

@book = Book.find book_id, :include => :pages

Now this where I'm confused. My understanding is that @book.pages is already loaded and won't execute another query. But suppose I want to find a specific page, what would I do?

@book.pages.find page_id

# OR...

@book.pages.to_ary.find{|p| p.id == page_id}

Am I right in thinking that the first example will execute another query, and therefore making the eager loading pointless, or is active record clever enough to know that it doesn't need to do another query?

Also, my second question, is there an argument that in some cases eager loading is more intensive on the database and sometimes multiple small queries will be more efficient that a single large query?

Thanks for your thoughts.

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about activerecord