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}")
}
Written by Alexander Tamoykin
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Activerecord
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#