Silly Error!

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

On 6/15/07, Armitage [email protected] 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

Thats perfect!

Thank you very much indeed

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs