简体   繁体   中英

Rails avoid N+1 query problem working with external and internal data

I have the following array coming from an external source :

documents = ['Doc Name 1', 'Doc Name 2', 'Doc Name 3', ...]

I want to loop through the array, and find details about the documents in my db (model Doc ) if it exists.

documents.each do |document|
  puts Doc.find_by_name(document).details if Doc.find_by_name(document)
end

Of course this code works, but how can I avoid the N+1 query problem?

Hope details is one of the columns in the table docs (plural of the model)

Try the below:

documents = ['Doc Name 1', 'Doc Name 2', 'Doc Name 3']

Doc.where(name: documents).pluck(:details)

It will trigger single query and selects value only the column details and returns the details in an array:

SELECT "docs"."details" FROM "docs" 
  WHERE "docs"."name" IN ('Doc Name 1', 'Doc Name 2', 'Doc Name 3')

If you have more data on the array documents please consider using batch processing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM