Problem with DateTime in query

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
<= ?”,
Time.zone.now.beginning_of_day.utc, Time.zone.now.end_of_day.utc]

If I start the server and use user.enrollments.today, 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 66.249.102.37 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 66.249.102.37 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 Time.zone.now.beginning_of_day.utc and
Time.zone.now.end_of_day.utc 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?

On 8 Oct 2008, at 16:36, cjharrelson wrote:

<= ?",
Time.zone.now.beginning_of_day.utc, Time.zone.now.end_of_day.utc]

The Time.zone.now 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 }

Fred

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
question.

On Oct 8, 8:54 am, Frederick C. [email protected]