# Initialize won't work?

**URL:** <https://www.ruby-forum.com/t/initialize-wont-work/170617>\
**Category:** Rails\
**Created:** [June 19, 2009, 6:40pm UTC](https://www.ruby-forum.com/t/initialize-wont-work/170617 "2009-06-19T18:40:56Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![himdel](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/h/c67d28/32.png) [@himdel](https://www.ruby-forum.com/u/himdel)\
**Post date:** [June 19, 2009, 6:40pm UTC](https://www.ruby-forum.com/t/initialize-wont-work/170617/1 "2009-06-19T18:40:56Z")

</div>

I’ve got a simple model

class ExtraType \< ActiveRecord::Base  
has\_many :match\_balls  
attr\_accessor :extra\_total  
def initialize  
self.extra\_total=0  
end  
end

When I try  
ex=ExtraType.new, I get  
INTERNAL ERROR!!! You have a nil object when you didn’t expect it!  
The error occurred while evaluating nil.has\_key?  
/Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active\_record/  
base.rb:2633:in `has\_attribute?’

I don’t think I’m doing anything daft here … or am I (It’s the end of  
a long week after all)  
Ruby 1.8.6 with Rails 2.2.2

---

<div class="post-metadata">

**Author:** ![himdel](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/h/c67d28/32.png) [@himdel](https://www.ruby-forum.com/u/himdel)\
**Post date:** [June 19, 2009, 6:40pm UTC](https://www.ruby-forum.com/t/initialize-wont-work/170617/2 "2009-06-19T18:40:56Z")

</div>

2009/6/19 Martin H. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid):

> When I try  
> ex=ExtraType.new, I get  
> INTERNAL ERROR!!! You have a nil object when you didn’t expect it!  
> The error occurred while evaluating nil.has\_key?  
> /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active\_record/  
> base.rb:2633:in `has\_attribute?’
> 
> I don’t think I’m doing anything daft here … or am I (It’s the end of  
> a long week after all)

I think you should call super in initialize otherwise it is not doing  
the base class initialize. Also watch out as I think rails does not  
always call new to instantiate an object so your initialize may not  
get called. See

> **[Rails: Don't override initialize on ActiveRecord objects](https://blog.dalethatcher.com/2008/03/rails-dont-override-initialize-on.html)**
>
> ActiveRecord::Base doesn't always use new to create objects, so initialize might not be called. I wanted to use a Hash on an ActiveRecord...

for example.

Colin

---

<div class="post-metadata">

**Author:** ![himdel](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/h/c67d28/32.png) [@himdel](https://www.ruby-forum.com/u/himdel)\
**Post date:** [June 19, 2009, 6:58pm UTC](https://www.ruby-forum.com/t/initialize-wont-work/170617/3 "2009-06-19T18:58:06Z")

</div>

Many thanks. Calling super fixed it.  
Doh - should have realised that - as I said - end of a long week.
