Forum: Ruby on Rails Storing an object in the db

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and 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


class MyRecord < ActiveRecord::Base

the table my_record would have a binary field, my_object, that would
store an object of MyAwesomeClass.  So I could do:
r =
r.my_object =

I saw that there's a serialize helper, where I'd put this in my AR
class MyRecord < ActiveRecord::Base
  serialize :my_object

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.

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

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

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

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)

# this class is going to be serialized
class C
	attr_accessor :a, :b
	def initialize( a, b )
		@a, @b = a, b
	def to_str
		a.to_s + ' ' + b.to_s

		obj='hi', 'there')  # create something to be serialized
		so =     # create a place to store objects = Marshal.dump obj # serialize obj                    # save serialized data in db
		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'

		obj = Marshal.load # reconstitute obj
		puts obj.to_str            # i'm alive!
This topic is locked and can not be replied to.