pratski
pratski

Reputation: 1488

Issue with filtering by age when Date of Birth is stored in Database

I have done quite a bit of research and haven't found anything of relevance. The issue is that my Users table has a DOB column. And my User model has an age method that calculates the users age. I am able to display the users age as follows: current_user.age and it works just fine. But I can't use age in a query as it is not an attribute in the User model. How do other website, for example dating websites provide a filter by age option? I can't imagine them having an age column in the database as it would be painful to keep updating it. In short, how can I filter results based on a range of ages provided by a User?

Upvotes: 0

Views: 731

Answers (1)

Dogbert
Dogbert

Reputation: 222128

Let's say you want to find users between and including ages 18 and 20 as of today, and you're storing the DOB in a field called dob.

A person exactly 18 years old today would have been born on Apr 6, 1995. And one who's turning 21 tomorrow would be born on Apr 7, 1993.

So you want users with DOB between and including Apr 5, 1993 and Apr 6, 1995.

18.years.ago.to_date
=> Thu, 06 Apr 1995
(20.years.ago + 1.day).to_date
=> Mon, 07 Apr 1993

You can use this now

User.where("dob >= ? AND dob <= ?", 20.years.ago + 1.day, 18.years.ago)

Upvotes: 2

Related Questions