Last Updated: February 25, 2016
·
1.322K
· fsproru

Frozen time in rails scope

There is one caveat when using a time inside the ActiveRecord named scope

class Task < ActiveRecord::Base
    scope :due_now, 
           where("tasks.time_due < #{Time.zone.now}")
end

Every time you call Task.due_now it uses the same time when Taks class was loaded into memory and not the current time when the scope is called. If you want Time.zone.now to be evaluated every time you call a scope, you need to wrap the body of your scope in lambda

scope :due_now, lambda { 
       where("tasks.time_due < #{Time.zone.now}") 
}