Answer the question
In order to leave comments, you need to log in
How not to call a query to the DB with each iteration?
There is such a code.
# BOOK model
belongs_to :author
# AUTHOR model
has_many :book
# CATEGORY model
has_many :author
def function
books.select{ |book| book.author.category.type.eql?('fantastic') }
end
def function
books
.includes({
author: {
category: {}
}
})
.select{ |book| book.author.category.type.eql?('fantastic') }
end
def function
Books
.includes({
author: {
category: {}
}
})
.where(id: books.pluck(:id))
.select{ |book| book.author.category.type.eql?('fantastic') }
end
Answer the question
In order to leave comments, you need to log in
# books здесь - ActiveRecord::Relation
books.includes(author: [:categories]).select do |book|
book.author.category.type == "fantastic"
end
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question