User.active return?class User < ApplicationRecord
scope :active, -> { where(active: true) }
end
users = User.activeThe scope active filters users where the active attribute is true, so User.active returns only those users.
class User < ApplicationRecord scope :recent, -> { where('created_at >= ?', 7.days.ago) } end
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.
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?class User < ApplicationRecord scope :active, -> { where(active: true) } scope :recent, -> { where('created_at >= ?', 7.days.ago) } end count = User.active.recent.count
Chaining active and recent scopes returns users who are both active and recent. Only 2 users meet both conditions.
class User < ApplicationRecord scope :min_age, ->(age) { where('age >= age') } end User.min_age(18)
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.
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.
