Question

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
Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top