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
You can use after_save callback like this
or before_save callback
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