Challenge - 5 Problems
Scope Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate2: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.activeAttempts:
2 left
💡 Hint
Think about what the where clause filters.
✗ Incorrect
The scope active filters users where the active attribute is true, so User.active returns only those users.
📝 Syntax
intermediate2: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
Attempts:
2 left
💡 Hint
Check how to pass dynamic values in SQL conditions.
✗ Incorrect
Option A correctly uses a SQL string with a placeholder and passes the dynamic value as a parameter. Other options either miss quotes or pass Ruby objects incorrectly.
❓ state_output
advanced2: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
Attempts:
2 left
💡 Hint
Chaining scopes combines their conditions with AND logic.
✗ Incorrect
Chaining active and recent scopes returns users who are both active and recent. Only 2 users meet both conditions.
🔧 Debug
advanced2: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)
Attempts:
2 left
💡 Hint
Look at how the parameter is used inside the where clause.
✗ Incorrect
The condition 'age >= age' compares the column to itself, not to the passed parameter. It should use a placeholder 'age >= ?' and pass age as argument.
🧠 Conceptual
expert2: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?
Attempts:
2 left
💡 Hint
Think about how scopes help avoid repeating the same query code.
✗ Incorrect
Scopes let you write query logic once and reuse it by calling the scope method. This keeps code DRY and easier to read and maintain.