Alias of Table?

I'm attempting to convert a legacy application.

I need to do what amounts to a "alias filter" on a table.
The table - call it 'Assets' - has many name-value pairs as its public data.
It is shared by many other tables, so the key is

     parent_id, parent_class

This is a one-way association: "Assets of X", where "X" can be another table.

In base SQL this is easy - set up an alias

My Question- ow to do this in Rails:
Is there a way to filter for a 'parent' class so this can be shared?

Class OneThing < AR::B
   has_many :assets # where asset.parent_class = 'OneThing'

Class AnotherThing < AR::B
   has_many :assets # where asset.parent_class = 'AnotherThing'

So how to make this 'automated' for the CRUD and how to define the 'Setting'
class? Can 'Asset' somehow belong_to more than one model?

I've no problem drawing the E-R diagram :slight_smile:
or thinking what the explicit and long winded SQL would be,
but I don't have the Rail experience to see this.

I can see docco on 'has_and_belongs_to_many' using an intermediate join
table, but this is a one way association.


Josh Susser said the following on 02/04/2007 12:06 PM:

Rails does this using something called a polymorphic association. It's
the only explicit support in Rails for composite foreign keys. Your
foreign key is composed of the values parent_id and parent_type. The
class name of the parent model is stored as a string in parent_type.

You set this up using the :polymorphic => true option on the :parent

  belongs_to :parent, :polymorphic => true

Then in the various classes, use :as => :parent on the has_many

  has_many :assets, :as => :parent

That seems odd to me, but what do I know. If I knew I wouldn't be asking :slight_smile:

So this would work:

class Asset < AR:B
   belongs_to :parent, :polymorphic => true

   def set(name, value)

   def value_of(name)

class Person < AR:B
   has_many :assets, :as => :parent

class Corporation < AR:B
   has_many :assets, :as => :parent

class Bank < Corporation
   has_many :assets, :as => :parent

class Government < AR:B
   has_many :assets, :as => :parent

class CIA < AR:B
   has_many :assets, :as => :parent

class Harry <AR:B
   has_many :assets, :as => :parent

   def make_my_asset(date, punkname)
       assetname = date.to_string

There are a few limitations related to this being a one-way association.

That's OK, I suppose, so long as you want to know the assets belonging to
something and not who owns a particular asset.

You can't do eager loading of parents, and has_many :through needs some
help to be useful. Otherwise it works pretty well.

Help? useful?
By 'help' do you mean if one of the parents needed to create or delete an
asset? Or does Rails 'magically' fill in the parent_id and parent_class

Would it help if these parents were a subclass of an AssetOwner class?