My tables are set up such that Child
has a 1:1
relationship with Parent
.
They share a primary key (id
):
Parent
hasid
andtype
andname
Child
hasid
andhealth
The Child
is a polymorphic inheritance of the Parent
. My goal is that Child.find(1)
should return a Child
object which responds to both name
and health
. The SQL statement would hypothetically look something like this:
SELECT parents.id, parents.name, childs.health FROM parents
LEFT JOIN childs ON childs.id = Parents.id
WHERE parents.id = 1 AND parents.type = 'Child' LIMIT 1
Thus I've attempted to use Polymorphic Inheritance in ActiveRecord:
class Parent < ApplicationRecord
class Child < Parent
When I attempt to execute Child.find(1)
, I see:
SELECT `parents`.* FROM `parents` WHERE `parents`.`type` IN ('Child') AND `parents`.`ID` = 1 LIMIT 1
=> #<Child id: 1, type: "Child", name: "Hello">
Notably, there's no JOIN
on the child
table, yet I receive a Child
object back. This leads to the unexpected behavior that the Child
object does not respond to health
. Curiously, if I add an explicit table association to the Child
class (self.table_name = "childs"
), then the query pattern changes to:
> c = Child.find(1)
Obtainable Load (0.3ms) SELECT `childs`.* FROM `childs` WHERE `childs`.`ID` = 2 LIMIT 1
Now I can access the health
, but not the type
or name
.
How can I correctly create this JOIN association such that an attempt to load a Child
object successfully JOINs the data from the parent?
Edit: these tables were created outside of an ActiveRecord migration (they are also accessed by other, pre-existing, non-Ruby applications) so I have no ability to change their schema. I can think of some fancy metaprogramming approaches, like responding to method_missing
, that might let me lazy-load the missing attributes through a join... but I'm afraid I'll end up having to re-implement a bunch of ActiveRecord, like delete
, create
, etc. (which will lead to bugs). So I'm looking for some native/clean(ish) way to accomplish this.