Polymorphic models


In my App, I have a design requirement where there are multiple types of requests for a given user. The user schema has id, email and so on..

The problem is I have at least 3 different kinds of requests, which have slight differences between each other (new fields here and there).
However, there is a lot of common functionality. Obviously, I would like to write the common functionality just once. In Rails, this would have been done with single table inheritance.

I’ve taken a look at the Abstract tables in Ecto and it doesn’t quite seem like it.
What would be the Ecto way of handling this problem?

Thanks again!

1 Like

In a nutshell, the best advice is: design it in the way it is best for the database because Elixir/Ecto will be able to handle the code reuse bits easily. It may even be a module named Request and then you have specific FooRequest, BarRequest, BazRequest for each type. There is no reason to worry about inheritance nor couple your DB design with your code, as single table inheritance in Rails would do, because in Elixir you can just pipe the data to the appropriate modules.

Abstract tables should work just fine with Ecto schema. Even in migrations, you can pass the options key when creating tables: https://hexdocs.pm/ecto/Ecto.Migration.html#table/2

Our belongs_to docs also talk about polymorphism a bit, so it may have relevant feedback: https://hexdocs.pm/ecto/Ecto.Schema.html#belongs_to/3

1 Like

I asked a similar question a while back: Composability of structs generated by Ecto Schemas

Maybe the replies there will be helpful.

I’ve done it with a tiny bit of meta programming and json fields, see this post for more info and code:

I came searching for the same information. As josevalim stated, the docs cover this pretty well and essentially go over some of the different SQL iheritance options but with information on how to implement with Elixir/Ecto.

To understand the solution I would first research SQL inheritance types (or just read this post: How to handle schemas polymorphism in Phoenix?)

Then go over to the docs to understand how to implement some of the “recommended” types:

1 Like