# Silly Error!

**URL:** <https://www.ruby-forum.com/t/silly-error/106913>\
**Category:** Rails\
**Created:** [June 15, 2007, 10:27am UTC](https://www.ruby-forum.com/t/silly-error/106913 "2007-06-15T10:27:58Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Armitage](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/779978/32.png) [@Armitage](https://www.ruby-forum.com/u/Armitage)\
**Post date:** [June 15, 2007, 10:27am UTC](https://www.ruby-forum.com/t/silly-error/106913/1 "2007-06-15T10:27:58Z")

</div>

What am I missing here?

Controller  
def add\_history  
@history = History.new  
Patient.find(params[:id]).history.create(params[:history])  
flash[:notice] = “Added History”  
redirect\_to :action =\>“show”, :id =\> params[:id]  
end

Models  
Patient  
has\_one :history  
History  
belongs\_to :patients

when I try to add a History I get

You have a nil object when you didn’t expect it!  
You might have expected an instance of ActiveRecord::Base.  
The error occured while evaluating nil.create

---

<div class="post-metadata">

**Author:** ![Armitage](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/779978/32.png) [@Armitage](https://www.ruby-forum.com/u/Armitage)\
**Post date:** [June 15, 2007, 11:24am UTC](https://www.ruby-forum.com/t/silly-error/106913/2 "2007-06-15T11:24:11Z")

</div>

On 6/15/07, Armitage [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> ```
> end
> 
> ```
> 
> You might have expected an instance of ActiveRecord::Base.  
> The error occured while evaluating nil.create

I believe your thinking that a has\_one assocaition has a create method  
like  
a has\_many. The has\_one association works a bit different. Your patient  
will have a create\_history method instead. You could rewrite this as

from  
def add\_history  
@history = History.new # Does nothing You don’t re-assign it.  
Patient.find(params[:id]).history.create( params[:history])

> ```
> flash[:notice] = "Added History"
> redirect_to :action =>"show", :id => params[:id]
> end
> 
> ```

to

def add\_history  
@history = Patient.find( params[:id] ).create\_history(  
params[:history] )  
|| History.new  
flash[:notice] = “Added History”  
redirect\_to :action =\> “show”, :id =\> params[:id]  
end

This will effectivley give the same functionality as you have.

You may want to add a bit of a rescue clause in the case that the  
Patient is  
not found. Or use find\_by\_id which doesn’t throw an Exception  
immediatley,  
but will when you call create\_history on nil.

Hope that helps  
Daniel

---

<div class="post-metadata">

**Author:** ![Armitage](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/779978/32.png) [@Armitage](https://www.ruby-forum.com/u/Armitage)\
**Post date:** [June 15, 2007, 12:00pm UTC](https://www.ruby-forum.com/t/silly-error/106913/3 "2007-06-15T12:00:17Z")

</div>

Thats perfect!

Thank you very much indeed
