Has_one with reference to the one stored in this object's ta


#1

I’m trying to build a system for generically storing an object graph,
on top of AR itself. The idea is to define one base class, and use
AR’s automatic single table inheritance to have it create the right
class.

Here’s what I have so far:

table generic_objects:
id int(11) not null auto_increment primary key
type varchar(255)

table generic_fields:
id int(11) not null auto_increment primary key
generic_object_id int(11) not null <-- points to its
owner
name varchar(255) not null
string_value varchar(255)
object_value_id int(11)
object_value_type varchar(255)

class GenericObject < ActiveRecord::Base
has_many :generic_fields, :dependent => :destroy
end

class GenericField < ActiveRecord::Base
belongs_to :generic_object
end

I then have some more magic code in GenericObject so that subclasses
can do things like this:

class Person < GenericObject
field :first_name, String
field :last_name, String
field :spouse, Person
end

So far everything is peachy. I can create and save Person objects and
set their fields.

But what if the model class has many of the linked object type? I’d
like to have the possibility for there to be multiple fields with the
same name, for has_many type relationships.

So at first I thought I could use has_many :through
=> :generic_fields, but I’d need to define a way from GenericField to
get at the linked object. I’d like to use has_one to represent this
many-to-one relationship, but it looks like that isn’t possible.

Since this was an experiment to try and find a way around the other
issue I have with AR, I’m tempted to give up this approach and try to
find some other kind of way to make arbitrary inheritance work.

TX