date.today 的named_scope Rails 2.3.9

发布于 2024-11-02 16:33:48 字数 411 浏览 1 评论 0原文

使用 Rails 2.3.9 应用程序并想知道如何编写我的named_scope,以便我只获得当前日期的workouts。我正在使用 before_filter 在应用程序控制器中设置时区。下面的内容不会引发错误,只是不会过滤:

workout.rb

named_scope :today_only, :conditions => [ "workouts.created_at <= ? AND workouts.created_at >= ?", Time.zone.now, 1.days.ago ]

application_controller.rb

before_filter :set_user_time_zone

Working with a Rails 2.3.9 app and wondering how to write my named_scope such that I only get workouts from the current date. I am setting the timezone in in the application controller with a before_filter. The below doesn't throw an error, just doesn't filter:

workout.rb

named_scope :today_only, :conditions => [ "workouts.created_at <= ? AND workouts.created_at >= ?", Time.zone.now, 1.days.ago ]

application_controller.rb

before_filter :set_user_time_zone

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

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

发布评论

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

评论(1

二智少女猫性小仙女 2024-11-09 16:33:48

您没有看到您想要的响应,因为 Ruby 在评估您的类定义时(而不是在您调用作用域时)评估您对 Time.now 的调用。您需要将 lambda 传递给您的 named_scope 调用,以使其对每个请求进行评估:

# ensure that Time.now is evaluated on every call
named_scope :today_only, lambda {{ :conditions => ["workouts.created_at BETWEEN ? AND ?", Time.zone.now.at_beginning_of_day, Time.zone.now.end_of_day ] }}

另外,我认为您的时间边界可能不正确。您是在查找过去 24 小时内(相对于 Time.now)创建的锻炼,还是仅查找“今天”创建的锻炼?您的示例适用于前者,上面的示例适用于后者。

You're not seeing the responses you want because Ruby is evaluating your call to Time.now when it evaluates your class definition, not when you're calling the scope. You need to pass a lambda to your named_scope call to get it to evaluate on every request:

# ensure that Time.now is evaluated on every call
named_scope :today_only, lambda {{ :conditions => ["workouts.created_at BETWEEN ? AND ?", Time.zone.now.at_beginning_of_day, Time.zone.now.end_of_day ] }}

Also, I think your Time boundaries may be incorrect. Are you looking for workouts that were created in the past 24 hours (relative to Time.now), or only workouts that were created "today?" Your example works for the former, the example above does the latter.

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