# serialized data is going to be stored here
class Serializedobj < ActiveRecord::Base
# this table has just two fields: id, data (type TEXT)
end
# this class is going to be serialized
class C
attr_accessor :a, :b
def initialize( a, b )
@a, @b = a, b
end
def to_str
a.to_s + '' '' + b.to_s
end
end
obj= C.new(''hi'', ''there'') # create
something to be serialized
so = Serializedobj.new # create a place to store objects
so.data = Marshal.dump obj # serialize obj
so.save # save serialized data in db
id = so.id # save id so we can restore obj later
so = nil
obj= nil
so = Serializedobj.find_by_id( id ) # try to find serialized obj
unless so
raise Exception, ''serialization failed''
end
obj = Marshal.load so.data # reconstitute obj
puts obj.to_str # i''m alive!
Pat Maddox wrote:
> I''ve asked this before, but never got a working response.
I''d like to
> store an object inside a binary field in my db. So I''d have a
class
> like this
>
> class MyAwesomeClass
> def do_something_awesome
> ...
> end
> end
>
> then
>
> class MyRecord < ActiveRecord::Base
> end
>
> the table my_record would have a binary field, my_object, that would
> store an object of MyAwesomeClass. So I could do:
> r = MyRecord.new
> r.my_object = MyAwesomeClass.new
> r.reload
> r.my_object.do_something_awesome
>
> I saw that there''s a serialize helper, where I''d put this
in my AR class:
> class MyRecord < ActiveRecord::Base
> serialize :my_object
> end
>
> But that doesn''t seem to be working, it just says my_object is a
> string, and none of the MyAwesomeClass methods are available to it.
> I''d really appreciate any help with this.
>
> Pat