Searching users based on their age from DOB value

106 views Asked by At

I have the Thinking Sphinx gem, and I am using it to replace my current advanced search setup.

I am storing the Users dob, and then converting it into a age in the User model.

User.rb:

def age
  now = Time.now.utc.to_date
  now.year - birthday.year - ((now.month > birthday.month || (now.month == birthday.month && now.day >= birthday.day)) ? 0 : 1)
end

I am not sure how I can add implement a search based on user ages. For example visitor selects ages from a double down box, 22 to 27. This should return users who are between the ages of 22 and 27.

How should this look if someone could provide an example?

3

There are 3 answers

1
aspencer8111 On BEST ANSWER

Wouldn't it make more sense to convert the user's dob into an age BEFORE saving, then just save the age to the DB? So in the controller, during the :create or :update methods, just run that method, and save age to the DB.

0
duffymo On

One way to accomplish it would be to add an age column along side the DOB entered by users and have a trigger that updates all ages once per day. You could index that easily and query using BETWEEN.

0
pat On

I would store the date of birth as a timestamp attribute, and then filter the Sphinx search results by a range of the first and last dates that are valid for the the age/ages you're after.

This avoids having your User model save the age (which will need to be updated regularly, both in the database and in Sphinx).