anithri
anithri

Reputation: 340

Will this work with named_scope in rails?

I can't find the answer to this anywhere, and I don't have the brainpower left today to think up a way to confirm it on my own.

I have a named scope like this...

named_scope :fresh, :conditions => ['updated_at > ?', 4.hours.ago]

And I don't know if that will work the way I want it to. Part of me thinks that the 4.hours.ago will be resolved when the class file is loaded, and the other part thinks that the 4.hours.ago will be expanded when it is used.

Thanks for the help!

Upvotes: 2

Views: 284

Answers (2)

dnch
dnch

Reputation: 9605

You'll need to use a lambda:

named_scope :fresh, lambda { { :conditions => ['updated_at > ?', 4.hours.ago] } }

The reason you need to use a lambda is because scopes are loaded when the app starts up. Because of this, the time in your scope would reflect the time in which your scope was loaded. So it may appear to work but would become more and more incorrect as time passed. By inserting the lambda you are telling that conditions hash to get executed every time the scope is called. Therefore the time call would not go stale.

Upvotes: 6

zetetic
zetetic

Reputation: 47548

class Person < ActiveRecord::Base
  named_scope :stale, :conditions => ['updated_at > ?', 4.hours.ago]
  named_scope :fresh, lambda {{ :conditions => ['updated_at > ?', 4.hours.ago] }}
end

produces:

> Person.stale
  SELECT * FROM "people" WHERE (updated_at > '2011-03-01 20:57:40') 
> Person.stale
  SELECT * FROM "people" WHERE (updated_at > '2011-03-01 20:57:40') # no change
> Person.fresh
  SELECT * FROM "people" WHERE (updated_at > '2011-03-01 20:57:59') 
> Person.fresh
  SELECT * FROM "people" WHERE (updated_at > '2011-03-01 20:58:01') 

Upvotes: 2

Related Questions