Bird
Raised Fist0
Ruby on Railsframework~20 mins

Scopes for reusable queries in Ruby on Rails - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Scope Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What does this scope return?
Given the following Rails model scope, what records will User.active return?
Ruby on Rails
class User < ApplicationRecord
  scope :active, -> { where(active: true) }
end

users = User.active
AAll users regardless of their active status
BAll users with active set to false
CAn error because the scope is not defined correctly
DAll users with the attribute active set to true
Attempts:
2 left
💡 Hint
Think about what the where clause filters.
📝 Syntax
intermediate
2:00remaining
Identify the syntax error in this scope definition
Which option shows the correct way to define a scope that returns users created in the last 7 days?
Ruby on Rails
class User < ApplicationRecord
  scope :recent, -> { where('created_at >= ?', 7.days.ago) }
end
Ascope :recent, -> { where('created_at >= ?', 7.days.ago) }
Bscope :recent, -> { where(created_at >= 7.days.ago) }
Cscope :recent, -> { where('created_at >= 7.days.ago') }
Dscope :recent, -> { where(created_at: 7.days.ago) }
Attempts:
2 left
💡 Hint
Check how to pass dynamic values in SQL conditions.
❓ state_output
advanced
2:00remaining
What is the output count of this chained scope?
Given these scopes, what is the count of User.active.recent.count if there are 5 active users, 3 users created in last 7 days, and 2 users who are both active and recent?
Ruby on Rails
class User < ApplicationRecord
  scope :active, -> { where(active: true) }
  scope :recent, -> { where('created_at >= ?', 7.days.ago) }
end

count = User.active.recent.count
A8
B2
C5
D3
Attempts:
2 left
💡 Hint
Chaining scopes combines their conditions with AND logic.
🔧 Debug
advanced
2:00remaining
Why does this scope raise an error?
This scope is intended to return users with a minimum age, but it raises an error. Why?
Ruby on Rails
class User < ApplicationRecord
  scope :min_age, ->(age) { where('age >= age') }
end

User.min_age(18)
AThe scope should use a hash instead of a string condition
BThe scope is missing a block parameter
CThe SQL condition uses a string 'age >= age' instead of a placeholder for the parameter
DThe scope is missing a call to .to_i on age
Attempts:
2 left
💡 Hint
Look at how the parameter is used inside the where clause.
🧠 Conceptual
expert
2:00remaining
How do scopes improve code reuse and readability in Rails?
Which option best explains the main benefit of using scopes for reusable queries in Rails?
AScopes allow defining common query logic once and reuse it easily, making code cleaner and easier to maintain
BScopes automatically cache query results to improve performance without extra code
CScopes replace the need for database indexes by optimizing queries internally
DScopes force all queries to be eager loaded to avoid N+1 problems
Attempts:
2 left
💡 Hint
Think about how scopes help avoid repeating the same query code.

Practice

(1/5)
1. What is the main purpose of using scopes in a Rails model?
easy
A. To define database table columns
B. To write controller actions
C. To create new database tables
D. To reuse common database queries easily

Solution

  1. Step 1: Understand what scopes do

    Scopes are defined in models to encapsulate common queries for reuse.
  2. Step 2: Identify the correct purpose

    They help avoid repeating query code by providing reusable query methods.
  3. Final Answer:

    To reuse common database queries easily -> Option D
  4. Quick Check:

    Scopes = reusable queries [OK]
Hint: Scopes are for reusable queries inside models [OK]
Common Mistakes:
  • Confusing scopes with database schema definitions
  • Thinking scopes create tables or columns
  • Mixing scopes with controller logic
2. Which of the following is the correct syntax to define a scope named active that selects records with status: 'active'?
easy
A. scope :active, -> { where(status: 'active') }
B. scope active: where(status: 'active')
C. def scope :active; where(status: 'active'); end
D. scope :active { where(status: 'active') }

Solution

  1. Step 1: Recall scope syntax

    Scopes use the syntax: scope :name, -> { query }.
  2. Step 2: Match the correct option

    scope :active, -> { where(status: 'active') } matches this syntax exactly with a lambda returning the query.
  3. Final Answer:

    scope :active, -> { where(status: 'active') } -> Option A
  4. Quick Check:

    Scope syntax = scope :name, -> { ... } [OK]
Hint: Use lambda with -> { ... } for scope queries [OK]
Common Mistakes:
  • Omitting the lambda syntax -> { ... }
  • Using incorrect method definitions for scopes
  • Missing colon before scope name
3. Given the following scopes in a Rails model:
scope :published, -> { where(published: true) }
scope :recent, -> { order(created_at: :desc) }

What will Article.published.recent.to_sql return?
medium
A. SELECT * FROM "articles" WHERE "articles"."published" = FALSE ORDER BY "articles"."created_at" ASC
B. SELECT * FROM "articles" ORDER BY "articles"."created_at" DESC WHERE "articles"."published" = TRUE
C. SELECT * FROM "articles" WHERE "articles"."published" = TRUE ORDER BY "articles"."created_at" DESC
D. SELECT * FROM "articles" WHERE "articles"."published" = TRUE

Solution

  1. Step 1: Understand scope chaining

    Chaining scopes combines their queries in order: published adds a WHERE clause, recent adds ORDER BY.
  2. Step 2: Analyze the SQL generated

    The SQL will filter published = true and order by created_at descending.
  3. Final Answer:

    SELECT * FROM "articles" WHERE "articles"."published" = TRUE ORDER BY "articles"."created_at" DESC -> Option C
  4. Quick Check:

    Chained scopes combine WHERE and ORDER BY [OK]
Hint: Chained scopes combine queries in order [OK]
Common Mistakes:
  • Placing ORDER BY before WHERE in SQL
  • Confusing true/false values in conditions
  • Ignoring scope chaining order
4. Identify the error in this scope definition:
scope :recent, { order(created_at: :desc) }
medium
A. Missing lambda syntax -> { ... } around the query
B. Incorrect scope name format
C. Using order instead of where
D. Scope must be defined in controller, not model

Solution

  1. Step 1: Check scope syntax requirements

    Scopes require a lambda (-> { ... }) to wrap the query for lazy evaluation.
  2. Step 2: Identify missing lambda

    The given scope uses curly braces without the lambda arrow, causing a syntax error.
  3. Final Answer:

    Missing lambda syntax -> { ... } around the query -> Option A
  4. Quick Check:

    Scopes need -> { ... } [OK]
Hint: Always wrap scope queries in -> { ... } [OK]
Common Mistakes:
  • Omitting the lambda arrow ->
  • Defining scopes outside models
  • Confusing order and where methods
5. You want to create a scope 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?
hard
A. scope :recent_active, -> { where(active: true).order('created_at >= 7.days.ago') }
B. scope :recent_active, -> { where(active: true).where('created_at >= ?', 7.days.ago) }
C. scope :recent_active, -> { where(active: true && created_at >= 7.days.ago) }
D. scope :recent_active, -> { where(active: true).where(created_at: 7.days.ago) }

Solution

  1. Step 1: Combine conditions with where

    Use chained where calls to combine multiple conditions logically ANDed.
  2. Step 2: Use correct date comparison syntax

    Use a SQL fragment with placeholder and 7.days.ago to compare dates properly.
  3. Final Answer:

    scope :recent_active, -> { where(active: true).where('created_at >= ?', 7.days.ago) } -> Option B
  4. Quick Check:

    Chain where with SQL and placeholders [OK]
Hint: Chain where with SQL and placeholders for complex conditions [OK]
Common Mistakes:
  • Using && inside where hash instead of chaining
  • Using order for filtering conditions
  • Comparing created_at with exact date instead of range
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard