Easily build a great vocabulary without studying! Now on the App Store!
Click here for more info about the app

Rails Find All by Birthday: How to Find Upcoming Birthdays with ActiveRecord


There are a few ways to solve this problem. However, I think the easiest is to cache the day of the year that the user is born on as an integer. If stored alongside the timestamp we can quickly get a list but properly handle the full birthday elsewhere, such as in the view. You don't want to rely on just the cached day of year because leap year is not accounted for.

The model will need both born_at and birthday columns.

create_table :users do |t|
  t.timestamp :born_at  # full timestamp
  t.integer :birthday   # just the day of year

The user model also needs a callback (before_save) to set and or update the cached birthday column based on the full timestamp. For convenience, a named scope can be added to the model which will let you call User.birthdays.

class User
  # User.birthdays
  scope :birthdays, lambda { where('birthday in(?)', 7.times.map{|i| Time.now.yday + i}) }

def before_save self.birthday = born_at.yday end end

You could also use the week in year (1 - 52) for the cache. Using the day you can look an arbitrary number of days ahead.

Tagged w/ #active record #activerecord #birthdays #cache counter #datetime #how to #scopes #timestampruby on rails