Ruby on Rails: Use a datetime instead of a boolean database field
Learn why using a datetime instead of a boolean in your Rails models gives you more useful data for almost no extra cost.
The problem
When tracking whether an action has occurred, it’s tempting to use a boolean field. I had the task of tracking if a phone number has been sent to a user(based on some logic that doesn’t matter right now) and I chose the boolean route:
1
t.boolean "is_phone_number_sent_to_user", default: false
This works, but you lose valuable information: when did it happen? This timestamp is often useful for debugging, analytics, or business logic later on.
The solution
Instead of using a boolean, use a datetime field. If the field is nil, the action hasn’t happened yet. If it has a value, the action occurred at that time:
1
t.datetime "phone_number_sent_to_user_at"
Here’s how you’d use it in your Rails model:
1
2
3
4
5
6
7
8
9
10
class User < ApplicationRecord
def phone_number_sent_to_user?
phone_number_sent_to_user_at.present?
end
def send_phone_number_to_user
# Your logic to send the phone number
update(phone_number_sent_to_user_at: Time.current)
end
end
Now you can check if it was sent (user.phone_number_sent_to_user?) and also know exactly when it happened (user.phone_number_sent_to_user_at). The storage cost is minimal, and you get valuable timestamp data almost for free.
Conclusion
Using datetime instead of boolean gives you the same functionality (checking if something happened) plus the added benefit of knowing when it happened. It’s almost free in terms of storage, and you’ll thank yourself later when you need that timestamp information.