named_scope for date.today Rails 2.3.9
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 c开发者_运维百科ontroller 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
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.
精彩评论