Named_scope and Time.zone


#1

So I’m trying to use a named scope to show upcoming events like so:

class Event
named_scope :upcoming, :conditions => [“starts_at >= ?”,
Time.zone.now.beginning_of_day]
end

In my application controller I am setting up the current time zone in
a before filter. The times that I display throughout the application
are all showing up correctly (in the current time zone). The problem
is that when I use this named scope to do searches it seems to use the
local system time zone rather than the time zone that I am specifying
in the application controller. Any idea why this might be occurring?


#2

I’ve been doing a bit more experimenting and it only happens in
production. Both boxes are using the same gems (rails 2.3.2). I
found a temporary solution which was creating a class method named
“upcoming” and using the same exact conditions.


#3

On Apr 25, 1:50 pm, Colin L. removed_email_address@domain.invalid wrote:

I am no expert on this, but since no-one else has responded I will have a
go. I think it may be that the date value for your named scope is
calculated when the file is loaded, not each time the named scope is used.
In development the files are reloaded at each request so all is well. In
production they are loaded only once. I think you need to use the lambda
syntax in the named scope to force it to recalculate each time.

Spot on, lambdas are the way to go here.

Fred


#4

Smacks forehead Thanks Colin & Frederick for the responses - it
makes sense now. I modified to use lambdas and it seems to be working
as expected:

class Event
named_scope :upcoming, lambda {
{ :conditions => [“starts_at >= ?”,
Time.zone.now.beginning_of_day] }
}
end


#5

I am no expert on this, but since no-one else has responded I will have
a
go. I think it may be that the date value for your named scope is
calculated when the file is loaded, not each time the named scope is
used.
In development the files are reloaded at each request so all is well. In
production they are loaded only once. I think you need to use the
lambda
syntax in the named scope to force it to recalculate each time. See
http://workswithruby.com/tags/named_scope for example.

2009/4/25 ionlydoeyes removed_email_address@domain.invalid