Forum: Ruby on Rails One Model from two Tables with no foreign keys

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
martin (Guest)
on 2006-02-19 20:12
(Received via mailing list)
I would like to create a model that is based on two database tables:

Table1
---------
id (PK)
data1

Table2
----------
id (PK)
data2

There is a one-to-one relationship between the records of Table1 and
Table2. (That is, for every record in Table1 there is a record with
matching id in Table2 and vice versa).

The problem is that I cannot alter the table schemas in any way, so I
cannot add tableX_id columns to create foreign key relationships.

What would be the proper implementation of this problem?

If it makes matters easier, I only require read access.

Thank you in advance for the help!
Gregory S. (Guest)
on 2006-02-20 03:01
(Received via mailing list)
On Sun, Feb 19, 2006 at 10:09:37AM -0800, martin wrote:
} I would like to create a model that is based on two database tables:
}
} Table1
} ---------
} id (PK)
} data1
}
} Table2
} ----------
} id (PK)
} data2
}
} There is a one-to-one relationship between the records of Table1 and
} Table2. (That is, for every record in Table1 there is a record with
} matching id in Table2 and vice versa).
}
} The problem is that I cannot alter the table schemas in any way, so I
} cannot add tableX_id columns to create foreign key relationships.
}
} What would be the proper implementation of this problem?

Pick one to be the "primary" table and the other to be the "dependent"
table. Use has_one with an explicit column name for the "foreign" key.
In
the model class you can add extra accessors that give the dependent
table's
fields, so it looks like a single record. I think there's another
parameter
to has_one that says that it should load the row from the dependent
table
up front, rather than lazily waiting for an access, which may or may not
be
desirable.

If you're feeling extra clever you can even override method_missing to
create accessors for dependent fields rather than explicitly writing
them,
but that's probably unnecessary.

} If it makes matters easier, I only require read access.

Doesn't matter, except that you only need accessors, not mutators.

} Thank you in advance for the help!
--Greg
This topic is locked and can not be replied to.