Forum: Ruby on Rails Problem with DateTime in query

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
cjharrelson (Guest)
on 2008-10-08 19:37
(Received via mailing list)
Here is a strange one for you:

I am using rails 2.1.0.  I am also using the Time zones feature.

I have a User model that has many enrollments.  The Enrollments model
has several named scopes, one of which is today:

# This named scope is adjusted to UTC
named_scope :today, :conditions => ["updated_at >= ? AND updated_at
<= ?",,]

If I start the server and use, I get back
today's enrollments, as you would expect.  Once tomorrow arrives, and
I utilize the same query, I get yesterday's enrollments.  I have put
the server's logger in debug mode to capture the queries and sure
enough, it is asking for yesterday's enrollments.

First day's log:

Processing CoursesController#show (for at 2008-10-07
13:24:35) [GET]
maxed_out_hours_for_today?() begin
calculate_hours_today() begin
hours_today: 0.0
   [4;36;1mEnrollment Load (0.001272) [0m    [0;1mSELECT * FROM
`enrollments` WHERE (`enrollments`.user_id = 213) AND (((updated_at >=
'2008-10-07 04:00:00' AND updated_at <= '2008-10-08 03:59:59') AND
(mode = 'evaluated')) AND (exam_id IS NULL))  [0m
Found 6 enrollments for user **********

Second day's log:

Processing CoursesController#show (for at 2008-10-08
07:22:19) [GET]
   [4;35;1mEnrollment Load (0.001750) [0m    [0mSELECT * FROM
`enrollments` WHERE (`enrollments`.user_id = 213) AND (((updated_at >=
'2008-10-07 04:00:00' AND updated_at <= '2008-10-08 03:59:59') AND
(mode = 'evaluated')) AND (exam_id IS NULL))  [0m
Found 6 enrollments for user *************

Notice that the dates are the same on both days.  This makes no sense
because and are what is being used in teh
named_scope.  It does not seem to be a time zone issue, as we are in
CDT, which is -5 from UTC right now.  The second day's query is
outside of the possible 5 hour overlap if I was making a mistake.

Does anyone have any idea what could be causing this?
Frederick C. (Guest)
on 2008-10-08 19:56
(Received via mailing list)
On 8 Oct 2008, at 16:36, cjharrelson wrote:

> <= ?",

The is evaluated precisely once: when the model is
loaded. Use a lambda (see the section on procedural scopes in the api
docs) to do something like

named_scope :today, lambda { :conditions => stuff here is evaluated
each time the scope is accessed }

Bosco So (Guest)
on 2008-10-08 21:07
(Received via mailing list)
Ryan B.' screencast on this topic -
- has more details about delaying evaluation of the condition with a
lambda (including optional argument).

How weird, I literally just watched his screencast before reading this

On Oct 8, 8:54 am, Frederick C. <removed_email_address@domain.invalid>
This topic is locked and can not be replied to.