now available

now available
Want fresh tech tips in your inbox?

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

Apps I've Built

XPath Expression Editor
Practice and improve your XPath skills with XPath Editor
Click to buy on the App Store
Photo Location Changer
Easily change the location on your photos and videos
Click here for more info about the app
Photo Date Changer
Easily change the dates and times on your photos and videos
Click here for more info about the app
English dictionary with notifications so you won't forget what you're studying!
Click here for more info about the app
The app that quizzes and scores you on your vocabulary!
Click here for more info about the app