I’m running Rails 1.2.3, as a precursor.
I’ve recently discovered some odd behavior in how Rails treats objects
saved in the session and its associations.
class Foo < ActiveRecord::Base
has_one :bar
has_one :barfoo
end
foo = Foo.new
foo.build_bar
session[:myfoo] = foo
POST
foo = session[:myfoo]
foo.new_record? -> true
foo.bar.nil? -> false
foo.save
foo.build_barfoo
foo.barfoo.nil? -> false
foo.barfoo.new_record? -> true
session[:myfoo] = foo
POST
foo = session[:myfoo]
foo.new_record? -> false
foo.barfoo.nil? -> true # This is the problem!
It looks like what happens is that if you store an object in the
session, associations get stripped from the object before
serialization IF object.new_record? == false. This is good, most of
the time, as it keeps the session size down. However, when the
association is unsaved, this is bad. I’m doing a process like so:
Object created -> association #1 created -> object and association
updated with form data and stored in the session -> preview is
rendered -> on confirm, object in session is saved.
Later,
Object loaded from DB -> association #2 created -> association #2
updated with form data -> object stored in session -> preview rendered
-> on confirm, should save the object and its association, but the
association is now nil.
Is this a bug? Should unsaved associations not be stripped, or am I
using the wrong design pattern here?
My workaround was to store the association object in the session and
to manually reassociate it with the object on each page load, but
that’s really kludgy and I’d prefer a more elegant solution if
possible. This feels like a bug, though, and it caused me to lose
multiple hours tracking it down - it is certainly not intuitive in the
slightest.