Search code examples
ruby-on-railsthinking-sphinx

Searching users based on their age from DOB value


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?


Solution

  • 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.