开发者

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!


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.


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') 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜