0

New to Tire and trying to figure out how to search a DOB ( Day Of birth ) column in my Profile model.

  • Try to build a simple search where I can set the age_from and age_to ( say 20 to 60 )
  • How can I do this since I only have a dob field?
  • Would it be better to calculate the age upon record creation and store it in a column and add that to my Profile model to clean the searching ?

What would be the best approach on this? thx

Rubytastic
  • 15,001
  • 18
  • 87
  • 175

2 Answers2

4

If your model has a dob field, then you can just do a query like so:

Profile.where(:dob => date_from..date_to)

You can pre-calculate date_from and date_to on the basis of whatever age you're trying to query for by doing something like Date.today-18.years and Date.today-24.years

Fareesh Vijayarangam
  • 5,037
  • 4
  • 23
  • 18
  • Ended up calculating the age as a integer to a seperate field, all true the app I was calculating the age based on dob while it now calc on record save – Rubytastic Aug 31 '12 at 13:14
1

To do it with scopes, you could do:

scope :age_from, lambda { |age| 
 { :conditions => ["profiles.dob >= ?", DateTime.now << (12* age)] } 
}

scope :age_to, lambda { |age| 
 { :conditions => ["profiles.dob <= ?", DateTime.now << (12* age)] } 
}
Kenny Grant
  • 9,360
  • 2
  • 33
  • 47