← Back to Upcase

App returning wrong date-related data


(Mark Gibson) #1

I have an app that displays historical information on bands & musicians. Part of it produces an “On this day” type page which looks like this:

On this day in Aussie Music for the 26th of January:
Born Today

  • Doug Ford turns 69 today
    ** David Briggs turns 63 today*

First Charting Today

  • The Single Please Don’t Ask Me by John Farnham first charted on this day in 1981*

The problem I’m having is that the birthdays it displays can sometimes be related to the wrong date. The output should always be related to “today” as in “On this day in …”.

The controller looks like this:

def daily_update
     @birthdays = Person.born_this_month.birthday_today.order_by_birthyear
     @recordings = Recording.first_charted_today.order_by_first_charted_year
 end

@recordings is always correct but @birthdays sometimes show yesterdays data instead of today’s. I’m using the acts_as_birthday gem to pull out the recordings via a date column called first_charted.

To retrieve the correct list for birthdays is a bit more complicated and I suspect this is where my problem will be. Instead of a single date column Birthdays are recorded using three separate columns for birth year, month & day. The reason it is done like this is that we need to record incomplete information sometimes. For example we may know the day & month of someones birthday but not the year.

@birthdays are found like so:

scope :born_this_month, where(:birth_month => Time.zone.now.month)
scope :birthday_today, where(:birth_day =>  Time.zone.now.day)

At first I thought it was a time zone issue but I’m confident the app configured properly. The app is hosted on Heroku and all the config variables look fine for my time zone. If I re-start the server, the problem disappears and the correct date is shown. Could it be a caching thing that gets cleared with a server re-boot?

All help gladly appreciated.


(Robert Lee-Cann) #2

Rails will automatically cache scopes, to keep things running nice and fast. However, for things that change, such as relative dates, this causes the problems you have experienced.

The solution is to wrap the scope parameters in a lambda. This means that they are evaluated every time they are used, rather than when the application loads.

See http://guides.rubyonrails.org/active_record_querying.html#scopes for further details.


(Mark Gibson) #3

Thanks so much Leeky, I thought it might be cache related.

Much appreciated. :smile: