0

In rails how could I calculate the age based on :dob date field after creating, saving and updating a profile object?

I have this method in my model:

  def set_age
    bd = self.dob
    d = Date.today
    age = d.year - bd.year
    age = age - 1 if (
    bd.month > d.month or
        (bd.month >= d.month and bd.day > d.day)
    )
    self.age = age.to_i
  end
Rubytastic
  • 15,001
  • 18
  • 87
  • 175

1 Answers1

1

You can use after_save callback like this

after_save: set_age

def set_age
    bd = self.dob
    d = Date.today
    age = d.year - bd.year
    age = age - 1 if (
    bd.month > d.month or
        (bd.month >= d.month and bd.day > d.day)
    )
    self.age = age.to_i
    self.save
  end

or before_save callback

before_save: set_age

def set_age
    bd = self.dob
    d = Date.today
    age = d.year - bd.year
    age = age - 1 if (
    bd.month > d.month or
        (bd.month >= d.month and bd.day > d.day)
    )
    self.age = age.to_i
  end

before_save is better than after_save as it will commit changes once.

I also think you neednot have a column age as age should always be derived on fly.

Thanks

Paritosh Singh
  • 6,288
  • 5
  • 37
  • 56
  • This also still doesent seem to work, I changed the set_age to self.age = 10 to be sure the calculation is not wrong, to no avail – Rubytastic Oct 02 '12 at 17:32
  • Ok, it seems your code and example is fully correct. It seems that the rake task I use to generate new records (test populate task ) is messing around -somehow- it calculates this value off a datetime field wich Is in the right format. Have to look into that, your answer is the correct one so I will accept the answer – Rubytastic Oct 02 '12 at 17:38