为什么在活动记录范围中使用lambdas

mai*_*aik 2 ruby ruby-on-rails-3

我正在阅读Beginning Rails 3.这本书创建了一个用户可以发布文章的项目.现在在Article对象中,他们创建了3个范围,如下所示:

scope :published, where("articles.published_at IS NOT NULL")
scope :draft, where("articles.published_at IS NULL")
scope :recent, lambda { published.where("articles.published_at > ?", 1.week.ago.to_date)}
Run Code Online (Sandbox Code Playgroud)

现在lambda我可以用这个scope语句替换它的最后一个函数,我得到了相同的结果:

scope :recent, where("published_at > ?", 1.week.ago.to_date)
Run Code Online (Sandbox Code Playgroud)

在这里使用lambda有什么好处?

rub*_*ish 10

如果不使用lambda,1.week.ago则会在应用程序启动时计算并缓存.因此,即使您的应用程序已运行数月,它仍将指向应用程序启动前一周的时间.

您在开发环境中没有注意到这一点,因为应用程序代码会在每个请求上重新加载.使用lambda,即使在生产环境中,也可以确保每次调用范围时都计算新值.