Help me understand Rails eager loading
- by aaronrussell
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.