Panasonic Youth rob sanheim writes about software, business, ruby, music, stuff and things



Posted
23 July 2008 @ 1am

Tagged
Rails, Ruby

Discuss

Quick: Find the Bug or Gotcha with named_scope

Think fast! Where's the bug?

RUBY:
  1. named_scope :active, :conditions => ["activated_at <= ?", DateTime.now.utc.to_s(:db)]

Looks fine, right? Maybe you've hit this already, and you see it immediately.

The symptoms are that the DateTime.now always seems to be a bit off - maybe you just restarted your server and its a only a few minutes off.

The bug is that DateTime.now gets evaluated at the time the class is loaded, not when the finder is run. What makes this easy to miss is that it will always work fine in tests and development, as everything is constantly getting reloaded there.

The fix, obvious once you've spent a combined time of over an hour trying to figure out what is going on:

RUBY:
  1. named_scope :active, lambda { { :conditions => ["activated_at <= ?", DateTime.now.utc.to_s(:db)] } }


3 Comments

Posted by
Thorsten
23 July 2008 @ 2am

that’s surely not a bug, but but i understand that it’s a bummer the first time one gets across this.

Bu, it’s the same as with :if => conditions in validations:

if you want to match against something that’s not defined when the model gets loaded, use a Proc.


Posted by
ruby licious
23 July 2008 @ 6am

How about:

named_scope :active, :conditions => ["activated_at <= NOW()"]


Posted by
Rob Sanheim
24 July 2008 @ 7am

Thorsten: It surely is a bug in the developer’s code. I don’t mean a bug in Rails, of course.

Rubylicious: That’s great if your system timezone and the timezones in your database are the same.


Leave a Comment

Notes on testing Bj (Background Job) Git Clone vs cp -R –> WTF?