Forum: Ruby on Rails Storing an object in the db

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
42172acdf3c6046f84d644cb0b94642c?d=identicon&s=25 Pat Maddox (pergesu)
on 2005-12-17 07:59
(Received via mailing list)
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
114a64bf4e0cb600120f348b6447c258?d=identicon&s=25 Jennyw Jennyw (jennyw)
on 2005-12-17 08:25
You could try using a text field instead and storing the object in YAML
format.

To convert an object to YAML, do an_object.to_yaml.

To restore the object, do an_object = YAML::load(a_model.object)

Jen
Ce60c4f78a63b0695e4dafc4bd7964f7?d=identicon&s=25 Lou Vanek (Guest)
on 2005-12-17 16:30
(Received via mailing list)
# 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!
This topic is locked and can not be replied to.