这可以与rails中的named_scope一起使用吗?

发布于 2024-10-19 23:56:27 字数 279 浏览 5 评论 0原文

我在任何地方都找不到这个问题的答案,而且我今天也没有足够的脑力来想出一种方法来亲自确认它。

我有一个像这样的命名范围...

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

我不知道这是否会按照我想要的方式工作。我一部分认为 4.hours.ago 在类文件加载时会被解析,另一部分则认为 4.hours.ago 在使用时会被扩展。

感谢您的帮助!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

囍笑 2024-10-26 23:56:27

您需要使用 lambda:

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

您需要使用 lambda 的原因是因为作用域是在应用程序启动时加载的。因此,示波器中的时间将反映示波器加载的时间。因此,它可能看起来有效,但随着时间的推移会变得越来越不正确。通过插入 lambda,您可以告诉条件哈希在每次调用作用域时执行。因此时间调用不会变得陈旧。

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.

゛时过境迁 2024-10-26 23:56:27
class Person < ActiveRecord::Base
  named_scope :stale, :conditions => ['updated_at > ?', 4.hours.ago]
  named_scope :fresh, lambda {{ :conditions => ['updated_at > ?', 4.hours.ago] }}
end

产生:

> 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') 
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') 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文