D
D
Demigodd2019-05-29 09:58:01
Ruby on Rails
Demigodd, 2019-05-29 09:58:01

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

Connections can somehow confuse you, but that's not the point.
The problem is that with each iteration, a request is made to the DB .
I tried to solve the problem through includes .
def function
  books
    .includes({
      author: {
        category: {}
      }
    })
    .select{ |book| book.author.category.type.eql?('fantastic') }
end

But when called, it gives undefined method `includes' for #Array:0x000...
And if you take id and search on the model, is this a good solution?
def function
  Books
    .includes({
      author: {
        category: {}
      }
    })
    .where(id: books.pluck(:id))
    .select{ |book| book.author.category.type.eql?('fantastic') }
end

I will be glad to see your options for reducing queries to the DB with each iteration, since I no longer know what else can be done.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
blackst0ne, 2019-05-29
@blackst0ne

# 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 question

Ask a Question

731 491 924 answers to any question