SlideShare a Scribd company logo
1 of 6
Download to read offline
HOW TO FIX N+1 QUERY
WITH PRELOADING SCOPE
Reference articles:
Justin Weiss, How to Preload Rails Scopes and Why use scopes when we already have class methods?
Yiming Tsai @ Backer-Founder
SCOPE V.S. CLASS METHOD
class Reward
scope :updated_since, -> (time) { where(“reward.updated_at > ?”, time) }
#scope :updated_since, -> (time) { where(updated_at: (time..Time.now)) }
end
class self.updated_since(time)
if time.present?
where(“reward.updated_at > ?”, time)
else
all
end
end
Scope
Class
Method
Usage Reward.updated_since(1.day.ago)
Class
Method
Simple definition & Handle conditions for you
Complicated logic
SCOPE V.S. CLASS METHOD
Scope
HOW WE USUALLY FIX N+1 QUERY
Project.limit(5).map do |project|
project.rewards.length
end
class Project
has_many :rewards
end
class Reward
belongs_to :project
end
Project.includes(:rewards).limit(5).map do |project|
project.rewards.length
end
Model
N+1 query
Solution
WITH SCOPE..
Project.limit(5).map do |project|
project.rewards.publish.length
end
class Project
has_many :rewards
end
class Reward
belongs_to :project
enum [:draft, :publish]
end
Project.includes(:rewards).limit(5).map do |project|
project.rewards.publish.length
end
Model
N+1 query
Solution
SOLUTION
class Project
has_many :rewards
has_many :publish_rewards, -> { publish }, class_name: “Reward”
end
Project.includes(:publish_review).limit(5).map do |project|
project.publish_review.length
end
Model
Code

More Related Content

Viewers also liked

Grant Thornton pilotage de la performance
Grant Thornton pilotage de la performanceGrant Thornton pilotage de la performance
Grant Thornton pilotage de la performanceOlivier Rihouet
 
Biologia- Membran Celuar.
Biologia- Membran Celuar.Biologia- Membran Celuar.
Biologia- Membran Celuar.KunAlejo07
 
BlueRidge-gartner-supply-chain-planning-magic-quadrant-2016-report
BlueRidge-gartner-supply-chain-planning-magic-quadrant-2016-reportBlueRidge-gartner-supply-chain-planning-magic-quadrant-2016-report
BlueRidge-gartner-supply-chain-planning-magic-quadrant-2016-reportBlueRidgeInventory
 
Energia nuclear en el peru
Energia nuclear en el peruEnergia nuclear en el peru
Energia nuclear en el peruJaime Languasco
 
Математика. 2 клас. Методика підготовчої роботи і ознайомлення учнів 2-го кла...
Математика. 2 клас. Методика підготовчої роботи і ознайомлення учнів 2-го кла...Математика. 2 клас. Методика підготовчої роботи і ознайомлення учнів 2-го кла...
Математика. 2 клас. Методика підготовчої роботи і ознайомлення учнів 2-го кла...Електронні книги Ранок
 
Математика. 4 клас. Задачі з величинами: швидкість руху тіла, час руху та под...
Математика. 4 клас. Задачі з величинами: швидкість руху тіла, час руху та под...Математика. 4 клас. Задачі з величинами: швидкість руху тіла, час руху та под...
Математика. 4 клас. Задачі з величинами: швидкість руху тіла, час руху та под...Електронні книги Ранок
 

Viewers also liked (9)

Active record transaction
Active record transactionActive record transaction
Active record transaction
 
Grant Thornton pilotage de la performance
Grant Thornton pilotage de la performanceGrant Thornton pilotage de la performance
Grant Thornton pilotage de la performance
 
Biologia- Membran Celuar.
Biologia- Membran Celuar.Biologia- Membran Celuar.
Biologia- Membran Celuar.
 
iRviN pOrtFoliO 9
iRviN pOrtFoliO 9iRviN pOrtFoliO 9
iRviN pOrtFoliO 9
 
BlueRidge-gartner-supply-chain-planning-magic-quadrant-2016-report
BlueRidge-gartner-supply-chain-planning-magic-quadrant-2016-reportBlueRidge-gartner-supply-chain-planning-magic-quadrant-2016-report
BlueRidge-gartner-supply-chain-planning-magic-quadrant-2016-report
 
6 ano atmosfera
6 ano atmosfera6 ano atmosfera
6 ano atmosfera
 
Energia nuclear en el peru
Energia nuclear en el peruEnergia nuclear en el peru
Energia nuclear en el peru
 
Математика. 2 клас. Методика підготовчої роботи і ознайомлення учнів 2-го кла...
Математика. 2 клас. Методика підготовчої роботи і ознайомлення учнів 2-го кла...Математика. 2 клас. Методика підготовчої роботи і ознайомлення учнів 2-го кла...
Математика. 2 клас. Методика підготовчої роботи і ознайомлення учнів 2-го кла...
 
Математика. 4 клас. Задачі з величинами: швидкість руху тіла, час руху та под...
Математика. 4 клас. Задачі з величинами: швидкість руху тіла, час руху та под...Математика. 4 клас. Задачі з величинами: швидкість руху тіла, час руху та под...
Математика. 4 клас. Задачі з величинами: швидкість руху тіла, час руху та под...
 

Similar to How to Fix N+1 Query with Preloading Scope

Managing Uncertainties in Hardware-Software Codesign Projects
Managing Uncertainties in Hardware-Software Codesign ProjectsManaging Uncertainties in Hardware-Software Codesign Projects
Managing Uncertainties in Hardware-Software Codesign ProjectsJones Albuquerque
 
Dipso K Mi
Dipso K MiDipso K Mi
Dipso K Mimsabou
 
A457405934_21789_26_2018_Inheritance.ppt
A457405934_21789_26_2018_Inheritance.pptA457405934_21789_26_2018_Inheritance.ppt
A457405934_21789_26_2018_Inheritance.pptRithwikRanjan
 
JavaScript code academy - introduction
JavaScript code academy - introductionJavaScript code academy - introduction
JavaScript code academy - introductionJaroslav Kubíček
 
The Ring programming language version 1.5.2 book - Part 70 of 181
The Ring programming language version 1.5.2 book - Part 70 of 181The Ring programming language version 1.5.2 book - Part 70 of 181
The Ring programming language version 1.5.2 book - Part 70 of 181Mahmoud Samir Fayed
 
QA Fest 2018. Никита Кричко. Методология использования машинного обучения в н...
QA Fest 2018. Никита Кричко. Методология использования машинного обучения в н...QA Fest 2018. Никита Кричко. Методология использования машинного обучения в н...
QA Fest 2018. Никита Кричко. Методология использования машинного обучения в н...QAFest
 
The Ring programming language version 1.5.1 book - Part 69 of 180
The Ring programming language version 1.5.1 book - Part 69 of 180The Ring programming language version 1.5.1 book - Part 69 of 180
The Ring programming language version 1.5.1 book - Part 69 of 180Mahmoud Samir Fayed
 
The Ring programming language version 1.4.1 book - Part 20 of 31
The Ring programming language version 1.4.1 book - Part 20 of 31The Ring programming language version 1.4.1 book - Part 20 of 31
The Ring programming language version 1.4.1 book - Part 20 of 31Mahmoud Samir Fayed
 
2014 International Software Testing Conference in Seoul
2014 International Software Testing Conference in Seoul2014 International Software Testing Conference in Seoul
2014 International Software Testing Conference in SeoulJongwook Woo
 
The Ring programming language version 1.2 book - Part 53 of 84
The Ring programming language version 1.2 book - Part 53 of 84The Ring programming language version 1.2 book - Part 53 of 84
The Ring programming language version 1.2 book - Part 53 of 84Mahmoud Samir Fayed
 
The Ring programming language version 1.4 book - Part 20 of 30
The Ring programming language version 1.4 book - Part 20 of 30The Ring programming language version 1.4 book - Part 20 of 30
The Ring programming language version 1.4 book - Part 20 of 30Mahmoud Samir Fayed
 
Never-Ending Learning for Open-Domain Question Answering over Knowledge Bases
Never-Ending Learning for Open-Domain Question Answering over Knowledge BasesNever-Ending Learning for Open-Domain Question Answering over Knowledge Bases
Never-Ending Learning for Open-Domain Question Answering over Knowledge Basesrricha23
 
The Ring programming language version 1.8 book - Part 80 of 202
The Ring programming language version 1.8 book - Part 80 of 202The Ring programming language version 1.8 book - Part 80 of 202
The Ring programming language version 1.8 book - Part 80 of 202Mahmoud Samir Fayed
 
The Ring programming language version 1.7 book - Part 78 of 196
The Ring programming language version 1.7 book - Part 78 of 196The Ring programming language version 1.7 book - Part 78 of 196
The Ring programming language version 1.7 book - Part 78 of 196Mahmoud Samir Fayed
 

Similar to How to Fix N+1 Query with Preloading Scope (20)

L03 Software Design
L03 Software DesignL03 Software Design
L03 Software Design
 
Kaggle KDD Cup Report
Kaggle KDD Cup ReportKaggle KDD Cup Report
Kaggle KDD Cup Report
 
Managing Uncertainties in Hardware-Software Codesign Projects
Managing Uncertainties in Hardware-Software Codesign ProjectsManaging Uncertainties in Hardware-Software Codesign Projects
Managing Uncertainties in Hardware-Software Codesign Projects
 
Adding Game Elements
Adding Game ElementsAdding Game Elements
Adding Game Elements
 
Dipso K Mi
Dipso K MiDipso K Mi
Dipso K Mi
 
Java sessionnotes
Java sessionnotesJava sessionnotes
Java sessionnotes
 
A457405934_21789_26_2018_Inheritance.ppt
A457405934_21789_26_2018_Inheritance.pptA457405934_21789_26_2018_Inheritance.ppt
A457405934_21789_26_2018_Inheritance.ppt
 
Java assgnmt2.
Java assgnmt2.Java assgnmt2.
Java assgnmt2.
 
JavaScript code academy - introduction
JavaScript code academy - introductionJavaScript code academy - introduction
JavaScript code academy - introduction
 
The Ring programming language version 1.5.2 book - Part 70 of 181
The Ring programming language version 1.5.2 book - Part 70 of 181The Ring programming language version 1.5.2 book - Part 70 of 181
The Ring programming language version 1.5.2 book - Part 70 of 181
 
2java Oop
2java Oop2java Oop
2java Oop
 
QA Fest 2018. Никита Кричко. Методология использования машинного обучения в н...
QA Fest 2018. Никита Кричко. Методология использования машинного обучения в н...QA Fest 2018. Никита Кричко. Методология использования машинного обучения в н...
QA Fest 2018. Никита Кричко. Методология использования машинного обучения в н...
 
The Ring programming language version 1.5.1 book - Part 69 of 180
The Ring programming language version 1.5.1 book - Part 69 of 180The Ring programming language version 1.5.1 book - Part 69 of 180
The Ring programming language version 1.5.1 book - Part 69 of 180
 
The Ring programming language version 1.4.1 book - Part 20 of 31
The Ring programming language version 1.4.1 book - Part 20 of 31The Ring programming language version 1.4.1 book - Part 20 of 31
The Ring programming language version 1.4.1 book - Part 20 of 31
 
2014 International Software Testing Conference in Seoul
2014 International Software Testing Conference in Seoul2014 International Software Testing Conference in Seoul
2014 International Software Testing Conference in Seoul
 
The Ring programming language version 1.2 book - Part 53 of 84
The Ring programming language version 1.2 book - Part 53 of 84The Ring programming language version 1.2 book - Part 53 of 84
The Ring programming language version 1.2 book - Part 53 of 84
 
The Ring programming language version 1.4 book - Part 20 of 30
The Ring programming language version 1.4 book - Part 20 of 30The Ring programming language version 1.4 book - Part 20 of 30
The Ring programming language version 1.4 book - Part 20 of 30
 
Never-Ending Learning for Open-Domain Question Answering over Knowledge Bases
Never-Ending Learning for Open-Domain Question Answering over Knowledge BasesNever-Ending Learning for Open-Domain Question Answering over Knowledge Bases
Never-Ending Learning for Open-Domain Question Answering over Knowledge Bases
 
The Ring programming language version 1.8 book - Part 80 of 202
The Ring programming language version 1.8 book - Part 80 of 202The Ring programming language version 1.8 book - Part 80 of 202
The Ring programming language version 1.8 book - Part 80 of 202
 
The Ring programming language version 1.7 book - Part 78 of 196
The Ring programming language version 1.7 book - Part 78 of 196The Ring programming language version 1.7 book - Part 78 of 196
The Ring programming language version 1.7 book - Part 78 of 196
 

Recently uploaded

CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxk795866
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEroselinkalist12
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLDeelipZope
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfme23b1001
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxKartikeyaDwivedi3
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 

Recently uploaded (20)

young call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Serviceyoung call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Service
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptx
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCL
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdf
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptx
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 

How to Fix N+1 Query with Preloading Scope

  • 1. HOW TO FIX N+1 QUERY WITH PRELOADING SCOPE Reference articles: Justin Weiss, How to Preload Rails Scopes and Why use scopes when we already have class methods? Yiming Tsai @ Backer-Founder
  • 2. SCOPE V.S. CLASS METHOD class Reward scope :updated_since, -> (time) { where(“reward.updated_at > ?”, time) } #scope :updated_since, -> (time) { where(updated_at: (time..Time.now)) } end class self.updated_since(time) if time.present? where(“reward.updated_at > ?”, time) else all end end Scope Class Method Usage Reward.updated_since(1.day.ago)
  • 3. Class Method Simple definition & Handle conditions for you Complicated logic SCOPE V.S. CLASS METHOD Scope
  • 4. HOW WE USUALLY FIX N+1 QUERY Project.limit(5).map do |project| project.rewards.length end class Project has_many :rewards end class Reward belongs_to :project end Project.includes(:rewards).limit(5).map do |project| project.rewards.length end Model N+1 query Solution
  • 5. WITH SCOPE.. Project.limit(5).map do |project| project.rewards.publish.length end class Project has_many :rewards end class Reward belongs_to :project enum [:draft, :publish] end Project.includes(:rewards).limit(5).map do |project| project.rewards.publish.length end Model N+1 query Solution
  • 6. SOLUTION class Project has_many :rewards has_many :publish_rewards, -> { publish }, class_name: “Reward” end Project.includes(:publish_review).limit(5).map do |project| project.publish_review.length end Model Code