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
4

1 回答 1

1

您可以像这样使用 after_save 回调

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

或 before_save 回调

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 比 after_save 更好,因为它会提交一次更改。

我也认为你不需要列年龄,因为年龄应该总是在飞行中得出。

谢谢

于 2012-10-02T17:15:46.623 回答