Ruby on Rails: after you download an association that has conditions, how can you get it without touching the database again?

Imagine a simple example:

class Book
  has_many :chapters
end

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

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

Now let me say that I want to display the chapter. How can I address chapters in Rails without re-entering the database? If I do something like this:

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

Will Rails reuse the database for all partitions so that it can scan them, and then even worse, to scan them again in the controller code?

And it looks like something is using, for example:

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

forces the database to crash again, even if it is already cached.

+3
source share
1

: include = > : , 2 API AR. , . , book.chapters , .

, ActiveRecord , , Chapter.find_by_book_id_and_title ('title'), Book.chapters ( ).

+3

Source: https://habr.com/ru/post/1735375/


All Articles