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 Seidman
2006-Feb-20 01:00 UTC
[Rails] One Model from two Tables with no foreign keys
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
Possibly Parallel Threads
- Need help with a Power Find()
- Combine multiple tables into one
- sqldf and not converting integers to floating point in SQLite
- Displaying related tables in forms.. probably an easy question!
- [Bug 452] New: DNAT to internal network don't work with source routing and 2 uplinks