seddka
seddka

Reputation: 105

Calculate and display user age in the view

I have a date_field :born_in for age and i want to display the calculated user age in user profile instead of the regular date format mm/dd/yyyy

I found a method in this answer on how to calculate user's age but i don't know how to implement it in my rails app.

user_information.rb

class UserInformation < ApplicationRecord
  belongs_to :user

  has_one :gender, :dependent => :destroy
  accepts_nested_attributes_for :gender, :allow_destroy => true

  has_one :relationship, :dependent => :destroy
  accepts_nested_attributes_for :relationship, :allow_destroy => true
end

show.html.erb

<%= @user.user_information.try(:born_in) %>

Upvotes: 1

Views: 248

Answers (2)

seddka
seddka

Reputation: 105

before i tried @jamesc solution:

def calculated_age
    now = Time.now.utc.to_date
    now.year - dob.year - ((now.month > dob.month || (now.month == dob.month && now.day >= dob.day)) ? 0 : 1)
  end

but i got an error saying :

undefined local variable or method dob' for #<UserInformation:0x00007feccd3a0d60>

That's because dob was not defined in the calculated method .

This is the solution i came up with :

def age
    now = Time.current
    dob = self.born_in
    now.year - dob.year - ((now.month > dob.month || (now.month == dob.month && now.day >= dob.day)) ? 0 : 1)
  end

And in Users profile show.html.erb all i had to do is :

<%= @user.user_information.age %>

Upvotes: 0

jamesc
jamesc

Reputation: 12837

Put the method in your model as a property (instance function rather than class function ) then in your form just pop the result into the page. You have shown no code whatsoever so I can not give you a code example to fix your problem but something like this maybe

class Person ...
  ...

  def calculated_age
    now = Time.now.utc.to_date
    now.year - dob.year - ((now.month > dob.month || (now.month == dob.month && now.day >= dob.day)) ? 0 : 1)
  end

Then in your view

<%= @person.calculated_age #Or whatever your instance variable name is %>

You might also want to add a check that dob is not null and set an appropriate default in the model

This is exactly what models are for. Views should just render the information they are given Show more code next time and help people to help you.

Upvotes: 1

Related Questions