I have an interesting Active Record problem and I'm not quite sure what the cleanest solution is. The legacy database that I am integrating with has a strange wrinkle in its schema where one logical table has been 'partitioned' into several physical tables. Each table has the same structure, but contains data about different items.
I'm not great at explaining this clearly (as you can tell!). Let me try and explain with a concrete example. Let's say we have a Car, which has one or more Wheels. Normally we'd represent that with a Car table and a Wheels table like so:
CREATE TABLE cars (
`id` int(11) NOT NULL auto_increment,
`name` varchar(255),
;etc
)
CREATE TABLE wheels (
`id` int(11) NOT NULL auto_increment,
`car_id` int(11) NOT NULL,
`color` varchar(255),
;etc
)
So far, so good. But with the 'partioning' strategy that is in my legacy database it would look more like:
CREATE TABLE cars (
`id` int(11) NOT NULL auto_increment,
`name` varchar(255),
;etc
)
CREATE TABLE car_to_wheel_table_map (
`car_id` int(11) NOT NULL,
`wheel_table` varchar(255)
)
CREATE TABLE wheels_for_fords (
`id` int(11) NOT NULL auto_increment,
`car_id` int(11) NOT NULL,
`color` varchar(255)
)
CREATE TABLE wheels_for_buicks (
`id` int(11) NOT NULL auto_increment,
`car_id` int(11) NOT NULL,
`color` varchar(255)
)
CREATE TABLE wheels_for_toyotas (
`id` int(11) NOT NULL auto_increment,
`car_id` int(11) NOT NULL,
`color` varchar(255)
)
So here we have a set of wheels_for_x tables, and a car_to_wheel_table_map table which contains a mapping from car_id to the specific wheels_for_x which contains the wheels for a specific car. If I want to find the set of wheels for a car I first have to find out which wheels table to use via the car_to_wheel_table_map table, and then look up records in the wheel table specified in the car_to_wheel_table_map.
Firstly, can someone enlighten me as to if there is a standard name for this technique?
Secondly, does anyone have any pointers on how I can make this work in Active Record in a nice clean way. The way I see it I can either have a Wheel model where the table name can be defined per instance, or I can dynamically create Model classes at runtime with the correct table name as specified in the mapping table.
EDIT: Note that changing the schema to be closer to what AR wants is not an option. Various legacy codebases rely on this schema and cannot realistically be modified.