date.today 的named_scope Rails 2.3.9
使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您没有看到您想要的响应,因为 Ruby 在评估您的类定义时(而不是在您调用作用域时)评估您对 Time.now 的调用。您需要将
lambda
传递给您的named_scope
调用,以使其对每个请求进行评估:另外,我认为您的时间边界可能不正确。您是在查找过去 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 yournamed_scope
call to get it to evaluate on every request: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.