# Has\_one with reference to the one stored in this object's ta

**URL:** <https://www.ruby-forum.com/t/has-one-with-reference-to-the-one-stored-in-this-objects-ta/92018>\
**Category:** Rails\
**Created:** [April 14, 2007, 5:21pm UTC](https://www.ruby-forum.com/t/has-one-with-reference-to-the-one-stored-in-this-objects-ta/92018 "2007-04-14T17:21:35Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![trejkaz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/8797f3/32.png) [@trejkaz](https://www.ruby-forum.com/u/trejkaz)\
**Post date:** [April 14, 2007, 5:21pm UTC](https://www.ruby-forum.com/t/has-one-with-reference-to-the-one-stored-in-this-objects-ta/92018/1 "2007-04-14T17:21:35Z")

</div>

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
