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

Prach: A Feature-Rich Platform Empowering the Autism Community
Prach: A Feature-Rich Platform Empowering the Autism CommunityPrach: A Feature-Rich Platform Empowering the Autism Community
Prach: A Feature-Rich Platform Empowering the Autism Communityprachaibot
 
Main Memory Management in Operating System
Main Memory Management in Operating SystemMain Memory Management in Operating System
Main Memory Management in Operating SystemRashmi Bhat
 
Gravity concentration_MI20612MI_________
Gravity concentration_MI20612MI_________Gravity concentration_MI20612MI_________
Gravity concentration_MI20612MI_________Romil Mishra
 
Katarzyna Lipka-Sidor - BIM School Course
Katarzyna Lipka-Sidor - BIM School CourseKatarzyna Lipka-Sidor - BIM School Course
Katarzyna Lipka-Sidor - BIM School Coursebim.edu.pl
 
US Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionUS Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionMebane Rash
 
70 POWER PLANT IAE V2500 technical training
70 POWER PLANT IAE V2500 technical training70 POWER PLANT IAE V2500 technical training
70 POWER PLANT IAE V2500 technical trainingGladiatorsKasper
 
DEVICE DRIVERS AND INTERRUPTS SERVICE MECHANISM.pdf
DEVICE DRIVERS AND INTERRUPTS  SERVICE MECHANISM.pdfDEVICE DRIVERS AND INTERRUPTS  SERVICE MECHANISM.pdf
DEVICE DRIVERS AND INTERRUPTS SERVICE MECHANISM.pdfAkritiPradhan2
 
Computer Graphics Introduction, Open GL, Line and Circle drawing algorithm
Computer Graphics Introduction, Open GL, Line and Circle drawing algorithmComputer Graphics Introduction, Open GL, Line and Circle drawing algorithm
Computer Graphics Introduction, Open GL, Line and Circle drawing algorithmDeepika Walanjkar
 
multiple access in wireless communication
multiple access in wireless communicationmultiple access in wireless communication
multiple access in wireless communicationpanditadesh123
 
Forming section troubleshooting checklist for improving wire life (1).ppt
Forming section troubleshooting checklist for improving wire life (1).pptForming section troubleshooting checklist for improving wire life (1).ppt
Forming section troubleshooting checklist for improving wire life (1).pptNoman khan
 
Turn leadership mistakes into a better future.pptx
Turn leadership mistakes into a better future.pptxTurn leadership mistakes into a better future.pptx
Turn leadership mistakes into a better future.pptxStephen Sitton
 
CME 397 - SURFACE ENGINEERING - UNIT 1 FULL NOTES
CME 397 - SURFACE ENGINEERING - UNIT 1 FULL NOTESCME 397 - SURFACE ENGINEERING - UNIT 1 FULL NOTES
CME 397 - SURFACE ENGINEERING - UNIT 1 FULL NOTESkarthi keyan
 
STATE TRANSITION DIAGRAM in psoc subject
STATE TRANSITION DIAGRAM in psoc subjectSTATE TRANSITION DIAGRAM in psoc subject
STATE TRANSITION DIAGRAM in psoc subjectGayathriM270621
 
Triangulation survey (Basic Mine Surveying)_MI10412MI.pptx
Triangulation survey (Basic Mine Surveying)_MI10412MI.pptxTriangulation survey (Basic Mine Surveying)_MI10412MI.pptx
Triangulation survey (Basic Mine Surveying)_MI10412MI.pptxRomil Mishra
 
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTIONTHE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTIONjhunlian
 
Module-1-(Building Acoustics) Noise Control (Unit-3). pdf
Module-1-(Building Acoustics) Noise Control (Unit-3). pdfModule-1-(Building Acoustics) Noise Control (Unit-3). pdf
Module-1-(Building Acoustics) Noise Control (Unit-3). pdfManish Kumar
 
TEST CASE GENERATION GENERATION BLOCK BOX APPROACH
TEST CASE GENERATION GENERATION BLOCK BOX APPROACHTEST CASE GENERATION GENERATION BLOCK BOX APPROACH
TEST CASE GENERATION GENERATION BLOCK BOX APPROACHSneha Padhiar
 
Curve setting (Basic Mine Surveying)_MI10412MI.pptx
Curve setting (Basic Mine Surveying)_MI10412MI.pptxCurve setting (Basic Mine Surveying)_MI10412MI.pptx
Curve setting (Basic Mine Surveying)_MI10412MI.pptxRomil Mishra
 
Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...
Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...
Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...Sumanth A
 
Javier_Fernandez_CARS_workshop_presentation.pptx
Javier_Fernandez_CARS_workshop_presentation.pptxJavier_Fernandez_CARS_workshop_presentation.pptx
Javier_Fernandez_CARS_workshop_presentation.pptxJavier Fernández Muñoz
 

Recently uploaded (20)

Prach: A Feature-Rich Platform Empowering the Autism Community
Prach: A Feature-Rich Platform Empowering the Autism CommunityPrach: A Feature-Rich Platform Empowering the Autism Community
Prach: A Feature-Rich Platform Empowering the Autism Community
 
Main Memory Management in Operating System
Main Memory Management in Operating SystemMain Memory Management in Operating System
Main Memory Management in Operating System
 
Gravity concentration_MI20612MI_________
Gravity concentration_MI20612MI_________Gravity concentration_MI20612MI_________
Gravity concentration_MI20612MI_________
 
Katarzyna Lipka-Sidor - BIM School Course
Katarzyna Lipka-Sidor - BIM School CourseKatarzyna Lipka-Sidor - BIM School Course
Katarzyna Lipka-Sidor - BIM School Course
 
US Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionUS Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of Action
 
70 POWER PLANT IAE V2500 technical training
70 POWER PLANT IAE V2500 technical training70 POWER PLANT IAE V2500 technical training
70 POWER PLANT IAE V2500 technical training
 
DEVICE DRIVERS AND INTERRUPTS SERVICE MECHANISM.pdf
DEVICE DRIVERS AND INTERRUPTS  SERVICE MECHANISM.pdfDEVICE DRIVERS AND INTERRUPTS  SERVICE MECHANISM.pdf
DEVICE DRIVERS AND INTERRUPTS SERVICE MECHANISM.pdf
 
Computer Graphics Introduction, Open GL, Line and Circle drawing algorithm
Computer Graphics Introduction, Open GL, Line and Circle drawing algorithmComputer Graphics Introduction, Open GL, Line and Circle drawing algorithm
Computer Graphics Introduction, Open GL, Line and Circle drawing algorithm
 
multiple access in wireless communication
multiple access in wireless communicationmultiple access in wireless communication
multiple access in wireless communication
 
Forming section troubleshooting checklist for improving wire life (1).ppt
Forming section troubleshooting checklist for improving wire life (1).pptForming section troubleshooting checklist for improving wire life (1).ppt
Forming section troubleshooting checklist for improving wire life (1).ppt
 
Turn leadership mistakes into a better future.pptx
Turn leadership mistakes into a better future.pptxTurn leadership mistakes into a better future.pptx
Turn leadership mistakes into a better future.pptx
 
CME 397 - SURFACE ENGINEERING - UNIT 1 FULL NOTES
CME 397 - SURFACE ENGINEERING - UNIT 1 FULL NOTESCME 397 - SURFACE ENGINEERING - UNIT 1 FULL NOTES
CME 397 - SURFACE ENGINEERING - UNIT 1 FULL NOTES
 
STATE TRANSITION DIAGRAM in psoc subject
STATE TRANSITION DIAGRAM in psoc subjectSTATE TRANSITION DIAGRAM in psoc subject
STATE TRANSITION DIAGRAM in psoc subject
 
Triangulation survey (Basic Mine Surveying)_MI10412MI.pptx
Triangulation survey (Basic Mine Surveying)_MI10412MI.pptxTriangulation survey (Basic Mine Surveying)_MI10412MI.pptx
Triangulation survey (Basic Mine Surveying)_MI10412MI.pptx
 
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTIONTHE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
 
Module-1-(Building Acoustics) Noise Control (Unit-3). pdf
Module-1-(Building Acoustics) Noise Control (Unit-3). pdfModule-1-(Building Acoustics) Noise Control (Unit-3). pdf
Module-1-(Building Acoustics) Noise Control (Unit-3). pdf
 
TEST CASE GENERATION GENERATION BLOCK BOX APPROACH
TEST CASE GENERATION GENERATION BLOCK BOX APPROACHTEST CASE GENERATION GENERATION BLOCK BOX APPROACH
TEST CASE GENERATION GENERATION BLOCK BOX APPROACH
 
Curve setting (Basic Mine Surveying)_MI10412MI.pptx
Curve setting (Basic Mine Surveying)_MI10412MI.pptxCurve setting (Basic Mine Surveying)_MI10412MI.pptx
Curve setting (Basic Mine Surveying)_MI10412MI.pptx
 
Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...
Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...
Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...
 
Javier_Fernandez_CARS_workshop_presentation.pptx
Javier_Fernandez_CARS_workshop_presentation.pptxJavier_Fernandez_CARS_workshop_presentation.pptx
Javier_Fernandez_CARS_workshop_presentation.pptx
 

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