Nick Woods
2005-May-08 00:50 UTC
Automatic accessors for serialized attributes in single db text column?
Let''s say I have a database table named simple_items with two columns,
an integer primary key column (id) and a a varchar column (info).
I then start with a simple model for the table in a file
model/simple_item.rb with something like the following:
class SimpleItem < ActiveRecord::Base
serialize :info
end
Say I want to now add two serialized fields called first_name and
last_name to this class, I want them to be serialized and stored in
the info column, and I want accessors directly off of the SimpleItem
class for these items.
I know that I could do something like the following:
class SimpleItem < ActiveRecord::Base
serialize :info
def first_name
self.info ? self.info[''first_name''] : nil
end
def first_name=(value)
self.info = {} if !self.info
self.info[''first_name''] = value
end
def last_name
self.info ? self.info[''last_name''] : nil
end
def last_name=(value)
self.info = {} if !self.info
self.info[''last_name''] = value
end
end
This however seems a bit redundant, epecially given the dynamic and
automatic way fields and attributes are implemented in Rails, and if I
now want to add 15 more fields to be serialized into the info column I
need to add 30 more methods. This starts to quickly feel like
something that I should be able to do much more easily with something
automatic in Rails but I haven''t been able to figure out how.
It seems like there should be some syntax along the lines of the
following (I know this isn''t valid and probably would need to look a
bit different, but this is just a pseudo example)
class SimpleItem < ActiveRecord::Base
serialize :first_name => :info, :last_name => :info
end
or something like
class SimpleItem < ActiveRecord::Base
serialize_to_attribute :info => [:first_name, :last_name]
end
Any thoughts, ideas, suggestions? This seems like something that many
people would want to do (I''m planning to support various fields for
different subclasses of this base class and want to store all of their
attributes in this single info column using serialized values).
I suppose I could probably make a wrapper class of some sort that
Rails will treat as a db table row and then serialize all fields of
that fake row into the info field for the real row but I don''t know
exactly how to do this and there might already be an easier way. I''m
still a bit new to the game and don''t quite understand attribute
inheritance, etc. and maybe something related to that is the way to go
but I''m not sure.
Any help would be much appreciated,
Thanks,
Nick