Ruby on rails RubyonRails:一旦你';如果您加载了一个具有条件的关联,那么您如何在不再次接触数据库的情况下获得它?

Ruby on rails RubyonRails:一旦你';如果您加载了一个具有条件的关联,那么您如何在不再次接触数据库的情况下获得它?,ruby-on-rails,eager-loading,Ruby On Rails,Eager Loading,想象一下这样一个简单的例子: class Book has_many :chapters end book = Book.find(:first, :include => :chapters, :conditions => ['chapters.title = ?', "In the beginning"] chapters = book.chapters.select{|chapter| chapter

想象一下这样一个简单的例子:

class Book
  has_many :chapters
end
book = Book.find(:first, 
                 :include => :chapters, 
                 :conditions => ['chapters.title = ?', "In the beginning"]
chapters = book.chapters.select{|chapter| chapter.title == "In the beginning"}
chapters = Chapter.find_by_book_id_and_title(book.id, "In the beginning")
假设在我的控制器中,我执行以下操作:

class Book
  has_many :chapters
end
book = Book.find(:first, 
                 :include => :chapters, 
                 :conditions => ['chapters.title = ?', "In the beginning"]
chapters = book.chapters.select{|chapter| chapter.title == "In the beginning"}
chapters = Chapter.find_by_book_id_and_title(book.id, "In the beginning")
现在让我们假设我想展示这一章。如何在不再次访问数据库的情况下处理Rails中的章节?如果我这样做:

class Book
  has_many :chapters
end
book = Book.find(:first, 
                 :include => :chapters, 
                 :conditions => ['chapters.title = ?', "In the beginning"]
chapters = book.chapters.select{|chapter| chapter.title == "In the beginning"}
chapters = Chapter.find_by_book_id_and_title(book.id, "In the beginning")
Rails会重新编译所有章节的数据库,以便扫描它们,然后更糟糕的是,必须在控制器代码中再次扫描它们吗

它看起来像是这样使用find的:

class Book
  has_many :chapters
end
book = Book.find(:first, 
                 :include => :chapters, 
                 :conditions => ['chapters.title = ?', "In the beginning"]
chapters = book.chapters.select{|chapter| chapter.title == "In the beginning"}
chapters = Chapter.find_by_book_id_and_title(book.id, "In the beginning")

使数据库再次被命中,即使该章节已被缓存

使用:include=>:章节应将其全部取回,从而根据需要总共进行2次查询。从那里,您应该能够遍历数据,而无需再次接触数据库。这是一个简单的循环阅读的问题。在这一点上,所有的数据都应该在手边

请注意,ActiveRecord只缓存最后一个查询,因此通过执行不同的查询,如Chapter.find\u by\u book\u id\u和\u title('title')来查找上一本书。chapters查询不会被缓存(因为它完全不同)