想象一个像这样的简单案例:
class Book
has_many :chapters
end
假设在我的控制器中我做了这样的事情:
book = Book.find(:first,
:include => :chapters,
:conditions => ['chapters.title = ?', "In the beginning"]
现在假设我要显示章节。如何在不再次访问数据库的情况下解决 Rails 中的章节?如果我做这样的事情:
chapters = book.chapters.select{|chapter| chapter.title == "In the beginning"}
Rails 是否会重新访问所有章节的数据库,以便扫描它们,然后更糟糕的是,必须在控制器代码中再次扫描它们?
看起来像这样使用 find 的东西:
chapters = Chapter.find_by_book_id_and_title(book.id, "In the beginning")
即使章节已经被缓存,也会导致数据库再次被命中。