views:

313

answers:

2

In Ruby-on-Rails, this is called a "polymorphic association."

I have several Commentable things in my application, the tables for each are below:

Post
id | title | text | author (FK:Person.id) | ...

Person
id | name | ...

Photo
id | title | owner (FK:Person.id) | path | ...

I'd like to add a Comments table as follows:

Comments
id | commentable_type | commentable_id | text | author (FK:Person.id)

I understand that I lose the database's referential integrity this way, but the only other option is to have multiple Comments tables: PostComments, PersonComments, PhotoComments, ...

And now for the question:

How can I build a form that will grok how to do the lookup, first by getting the table name from Comments.commentable_type and then the id from Comments.commentable_id?

A: 

I believe many people make meta-tables for that sort of thing. Pretty much exactly as you described it.

Joe Philllips
+2  A: 

This technique is known colloquially in the SQL world as 'subclassing'. For a worked example (SQL Server syntax but is easily adapted for MS Access), see David Porta's blog..

In your scenario, the data items common to all comments would be in your Comments table; anything specific to each type would be in specialized tables such as PhotoComments, etc. Note the FK should be the two-column compound of the ID plus the type, something which is often overlooked but is essential to referential integrity here e.g. you don’t want something typed as a photo comment appearing in the PersonComments table.

onedaywhen
So how do you do the form for that? That is, what's a good UI approach?
James A. Rosen