# Nil handling in ActiveRecord et al

**URL:** <https://www.ruby-forum.com/t/nil-handling-in-activerecord-et-al/124440>\
**Category:** Rails\
**Created:** [December 28, 2007, 6:01pm UTC](https://www.ruby-forum.com/t/nil-handling-in-activerecord-et-al/124440 "2007-12-28T18:01:02Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Pito](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/e68b1a/32.png) [@Pito](https://www.ruby-forum.com/u/Pito)\
**Post date:** [December 28, 2007, 6:01pm UTC](https://www.ruby-forum.com/t/nil-handling-in-activerecord-et-al/124440/1 "2007-12-28T18:01:02Z")

</div>

My database has a column called birthday.

The model has a method:

def age  
return (birthday.nil? ? -1 : DateTime.now.year - birthday.year)  
end

When called from a validation method on a new record, I get:

NameError in ‘User should be valid’  
undefined local variable or method `birthday’ for #User:0x3285e58

My interpretation after some experimenting is that because it’s a new  
record and birthday is not initialized, activerecord doesn’t give me  
an accessor called birthday.

What is the ‘proper’ way to write the age method?

Thanks,

Pito

---

<div class="post-metadata">

**Author:** ![Pito](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/e68b1a/32.png) [@Pito](https://www.ruby-forum.com/u/Pito)\
**Post date:** [December 31, 2007, 5:44pm UTC](https://www.ruby-forum.com/t/nil-handling-in-activerecord-et-al/124440/2 "2007-12-31T17:44:52Z")

</div>

On 12/28/07, Pito [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> My database has a column called birthday.
> 
> The model has a method:
> 
> def age  
> return (birthday.nil? ? -1 : DateTime.now.year - birthday.year)

I think you may want self.birthday here.

> end

–  
Greg D.  
[http://destiney.com/](http://destiney.com/)
