views:

48

answers:

1

Imagine a simple case like this:

class Book
  has_many :chapters
end

Let's say in my controller I do something like this:

book = Book.find(:first, 
                 :include => :chapters, 
                 :conditions => ['chapters.title = ?', "In the beginning"]

Now let's say I want to display the chapter. How can I address the chapters in Rails without hitting the database again? If I do something like this:

chapters = book.chapters.select{|chapter| chapter.title == "In the beginning"}

will Rails rehit the database for all of the chapters so that it can scan them, and then worse yet, have to scan them all again in the controller code?

And it seems like something that uses find like this:

chapters = Chapter.find_by_book_id_and_title(book.id, "In the beginning")

causes the database to be hit again even if it the chapter is already cached.

+3  A: 

Using :include => :chapters should fetch it all back resulting in a total of 2 queries according to the AR Association API. From there you should be able to traverse the data without touching the database again. It's a simple matter of looping through book.chapters at that point, all the data should be on hand.

Note that ActiveRecord only caches the last query, so by doing a different query like Chapter.find_by_book_id_and_title('title') your prior Book.chapters query won't be cached (because it is entirely different).

bojo