Polymorhpic `has_one`?

I’ve got a schema that has an asset_type and asset_id. Depending on the asset_type, that asset could be (for example) a Refrigerator or an HVACZone.

I could define has_one :hvac_zone, HVACZone, foreign_key: :id, references: :asset_id, and repeat this for each asset type, knowing that all but one will be empty in every case. But that’s awkward.

It appears from the docs that there’s no way to define a polymorphic has_one :asset that will preload the right record type based on the asset_type.

Thoughts on the most elegant way to deal with this polymorphism?

Take a look at this article I wrote a while back, it might help you decide on the approach: Polymorphic associations with Ecto and Postgres.

Also, if you don’t mind handling it as an embedding, I’ve coded an ecto type that I’ve been using for quite a while in some projects, here’s a gist (still deciding if I make it its own thing): An Ecto type that allows handling polymorphic embeddings · GitHub.

1 Like