Session trouble

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

for example when I am in console

o =

dl =

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

when I am using the controller

delivery_location =[:delivery_location])
session[:order].delivery_location = delivery_location

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

class DeliveryLocation
belongs_to :order

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

Another example I seen was on the

class Citizen < ActiveRecord::Base
has_one :ss_number

class SSNumber < ActiveRecord::Base
belongs_to :citizen

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


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,


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.