rtdp
rtdp

Reputation: 2107

Strange Behavior with mongoid date range query. - Rails 3

I am running in very strange date range query problem. When I use DateTime.now.utc option to query database, the query date for DateTime.now is different that my current DateTime.now(i.e. one that's returned on console.)

My mogoid.yml uses-

use_utc: true

I have my named scope like this -

scope :running_auctions, {
       :where => { :end_time.gt => DateTime.now.utc },
       :order_by => [:end_time, "ASC"]
 }

And on console I can do this -

Loading development environment (Rails 3.0.7)

irb(main):001:0> Auction.running_auctions
=> #<Mongoid::Criteria
selector: {:end_time=>{"$gt"=>Fri Jul 22 00:42:38 UTC 2011}},
options:  {:sort=>[:end_time, "ASC"]},
class:    Auction,
embedded: false>

Notice that my date here is Fri Jul 22 00:42:38 UTC 2011

irb(main):002:0> DateTime.now
=> Fri, 22 Jul 2011 11:42:56 +0530

irb(main):003:0> DateTime.now.utc
=> Fri, 22 Jul 2011 06:12:59 +0000

Notice here that my datetime is Fri, 22 Jul 2011 06:12:59 +0000

What is making query date older than actual current date ? Does mogoid or mongodb doing caching there ? Please let me know if I am missing something.

UPDATE

Loading development environment (Rails 3.0.7)
irb(main):001:0> Auction.running_auctions(DateTime.now.utc)
=> #<Mongoid::Criteria
 selector: {:end_time=>{"$gt"=>Fri Jul 22 01:21:53 UTC 2011}},
 options:  {:sort=>[:end_time, "ASC"]},
 class:    Auction,
 embedded: false>

irb(main):002:0> DateTime.now.utc
=> Fri, 22 Jul 2011 06:52:03 +0000

Upvotes: 0

Views: 1454

Answers (1)

rubish
rubish

Reputation: 10907

You have to use a lambda there. As of now, the DateTime.now.utc is computed at application startup and cached with application code.

You need to write your scope as:

scope :running_auctions, lambda {
  {
    :where => { :end_time.gt => DateTime.now.utc },
    :order_by => [:end_time, "ASC"]
  }
}

Upvotes: 1

Related Questions