Performance: Scopes for reusable queries
This concept affects database query efficiency and page load speed by reusing query logic and reducing redundant database calls.
class User < ApplicationRecord scope :active, -> { where(active: true) } scope :recent, -> { where('created_at > ?', 1.month.ago) } scope :admins, -> { where(role: 'admin') } end User.active.recent.admins
User.where(active: true).where('created_at > ?', 1.month.ago).where(role: 'admin')
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Repeated inline queries | N/A | N/A | N/A | [X] Bad |
| Reusable scopes with chaining | N/A | N/A | N/A | [OK] Good |
scopes in a Rails model?active that selects records with status: 'active'?scope :name, -> { query }.scope :published, -> { where(published: true) }
scope :recent, -> { order(created_at: :desc) }Article.published.recent.to_sql return?published adds a WHERE clause, recent adds ORDER BY.scope :recent, { order(created_at: :desc) }recent_active that returns records which are both active: true and created in the last 7 days. Which is the correct way to define this scope?where calls to combine multiple conditions logically ANDed.7.days.ago to compare dates properly.Pass the test and this pattern moves unknown