Session trouble

I am having a problem with an assignment to an object stored in session.

for example when I am in console

o = NewOrder.new

dl = DeliveryLocation.new

o.delivery_location = dl #=> returns a delivery location object

o.delivery_loaction.save #=> returns true

when I am using the controller

delivery_location = DeliveryLocation.new(params[:delivery_location])
session[:order].delivery_location = delivery_location
session[:order].delivery_location.save

When it gets to session[:order].delivery_location = delivery_location I
get the error
You have a nil object when you didn’t expect it!
The error occurred while evaluating nil.klass

/association_proxy.rb:147:in raise_on_type_mismatch' /associations/has_one_association.rb:44:inreplace’
/associations.rb:900:in delivery_location=' /delivery_locations_controller.rb:21:increate’

my Order model has_one :delivery_location
my DeliveryLocation model belongs_to :order

Any suggestions would be awesome.

write a test suite

It seems that if I change my association to

class Order
has_many :delivery_locations
end

class DeliveryLocation
belongs_to :order
end

then just append the delivery _location object into the
delivery_locations array then it works… BUT, this is not what I
want.

Another example I seen was on the dev.rubyonrails.org

class Citizen < ActiveRecord::Base
has_one :ss_number
end

class SSNumber < ActiveRecord::Base
belongs_to :citizen
end

If I want this, but have to change it to Citizen has_many :ss_numbers
just to work there is a problem.

Looking through the rails files, it seems what is dying is
def raise_on_type_mismatch(record)
unless record.is_a?(@reflection.klass)

Hi Jeremy, I came across your post and was having a similar problem. To
solve it I found that I had to initialize my association (also a
belongs_to) when first storing the object in the session (in your case
session[:order]). In other words when first assigning session[:order]
make sure that the delivery_location is not nil. You may not have that
data collected yet (in my case I have multi-step wizard with a complex
object graph), but just be sure that the belongs_to relationship is
initialized. Otherwise Rails seems to throw that nil.klass error when
calling raise_on_type_mismatch because nil isn’t the same type as
DeliveryLocation. Go figure.

Hi Jeremy, there’s no attribute or attr_writer on the session called

delivery_location=

If you’re trying to simply save an object into a session, you can do
the following:

session[:order] = o

Now, you can pull it out by doing the following:

order = session[:order]

If you require further information, I would recommend referencing the
relevant section in AWDwRv2.

Good luck,

-Conrad

Keynan P. wrote:

write a test suite

Thanks. It didn’t show me anything different, but I did write a test and
I get the same thing.