Search code examples
castle-activerecordforeign-key-relationship

Can ActiveRecord HasMany/Belongs To use a non-PrimaryKey Column for the relation?


I'd like to have a parent-child hierarchy AND I'd like to have the concept of a "series-id" on the parent.

So the parent (if you updated it) would expire the old unique key.. keep the series id and insert a second row.

I'd like the children to "hang" off that series id rather than the unique id.

Do you know if it's possible for BelongsTo to link into a non primary key (yet unique via GUIDs) column?

Parent: UniqueId (guid), SeriesId (guid), Name, Description Child: UniqueId (guid), ParentId (always connects ot UniqueId-Above), Name, Description.

I know that foreign key relations really should have a "key" on one side of the relation however, by my GUIDs they are key-like.. but not really keys.

Its not a big deal but if I "expire" the parent by updating it's metadata i'd like to avoid having to "copy" all the children into the new copy of the parent.

Am I trying to do something that can't happen?


Solution

  • There's an option for belongs_to that lets you specify the relationship:

    :foreign_key
        Specify the foreign key used for the association. By default this is guessed to be the name of the association with an "_id" suffix. So a class that defines a belongs_to :person association will use "person_id" as the default :foreign_key. Similarly, belongs_to :favorite_person, :class_name => "Person" will use a foreign key of "favorite_person_id".