Age calculation in Ruby

datetime, ruby, ruby-on-rails

Solution

For the validator, you can use a custom method:

validate :over_18

def over_18
  if dob + 18.years >= Date.today
    errors.add(:dob, "can't be under 18")
  end
end

Problem

I'm trying to write a rails application but presently the display for the date of birth is shown like the normal date format, but I wouldl love to show in views the age instead The method I have in controller is below and I have a column DOb in my database for date of birthL ``` def age @user = user now = Time.now.utc.to_date now.year - @user.dob.year - (@user.dob.to_date.change(:year => now.year) > now ? 1 : 0) end ``` It shows like DOB: 23/5/2011, but I would like it to be age in years instead. How do I also put a validator that checks if age is below 18 years?

Original source

Related problems