Posts

Showing posts with the label ORM

[ORM] Eager Loading and N+1 Query Problem

What is N+1 query problem? When your code loads the children in a parent-child relationship via the parent, most ORM have lazy-loading enabled by default, so queries are issued for the parent record, and then one query for EACH child record. As you can expect, doing N + 1 queries instead of a single query will floor your database with queries; something to avoid.  Consider this code: #Articles model class Article < ActiveRecord::Base     belongs_to :author end  #Authors model class Author < ActiveRecord::Base     has_many :posts end If you then ran: #In our controller @recent_articles = Article.order(published_at: :desc).limit(5) #in our view file @recent_articles.each do |article|     Title: <%= article.title %>     Author:<%= article.author.name %> # <-- this will trigger N+1 query end You would send 6 (5+1) queries to the database. 1 to fetch 5 recent articles, and then 5 for their correspo...