named_scope is a pretty elegant way, I think, but if you take this route, you will want to use it using the lambda method so that time does not fall into the area when the application is initially loaded.
For example, this:
named_scope :last_month, :conditions => ['created_at > ? AND created_at < ?', Date.today.last_month.beginning_of_month, Date.today.beginning_of_month]
will work properly in the first month when your application will work, but incorrectly in the next month if the application does not restart.
But this:
named_scope :last_month, lambda { {:conditions => ['created_at > ? AND created_at < ?', Date.today.last_month.beginning_of_month, Date.today.beginning_of_month]}}
will work every time, because the lambda method is run on every call, overestimating Date.today s.
Ian terrell
source share