cvkmohan

cvkmohan

What is the best practice of implementing Single Table Inheritance in Ecto?

I mean, I have a Vehicle model, Car Model, Bus Model etc. - we know the drill right? :slight_smile:
There is a shared functionality and data model needed - and - each model will have some specific functionality.

Three Reasons Why You Shouldn’t Use Single Table Inheritance – (rhnh.net) - Well, I read this - and - have been avoiding using STI. Further, Ecto discourages polymorphic relations. Considering these cases, how does one implement such models?

Showing Posts 1 to 10

stefanchrobot

stefanchrobot

You can use changeset functions for that:

defmodule Vehicle do
  schema "vehicles" do
    field :type, Ecto.Enum, values: [:car, :bus]
    # ...
  end

  def create_car_changeset(attrs) do
    %__MODULE__{}
    |> change(%{type: :car})
    # pipe through create_vehicle_changeset() if you want to extract common stuff
    |> cast(attrs, [:car_attr_1, :car_attr_1])
    # ...
  end

  def create_bus_changeset(attrs) do
    # ...
  end
end

Alternatively, you can create separate schemas on top of a single table:

defmodule Car do
  schema "vehicles" do
    field :type, Ecto.Enum, values: [:car, :bus]
    # shared and car fields only
  end
end

defmodule Bus do
  schema "vehicles" do
    field :type, Ecto.Enum, values: [:car, :bus]
    # shared and bus fields only
  end
end

If you don’t like changeset functions you can inline them in the context module.

12
Post #1
cvkmohan

cvkmohan OP

Thanks a lot @stefanchrobot. On a lighter note, the answer came faster than the time I took to compose the question. :slight_smile:

stefanchrobot

stefanchrobot

Happy to help! I’ve used STI just recently, so I’ve been looking into this lately :wink:

cvkmohan

cvkmohan OP

If you do not mind to share - which method you have gone in to? Changesets or Separate schemas?
At first thought, I felt like, Changesets looked good when there is a lot of common ground.

LostKobrakai

LostKobrakai

Can you explain why do you need a single table? How about having busses, cars and vehicles, where busses belongs_to vehicles and cars belongs_to vehicles?

stefanchrobot

stefanchrobot

This means that you have the following DB schema:

table vehicles(id, reg_no, ...)
table busses(id, vehicle_id, ...)

This means that on the database level, you can have a vehicle that’s not referenced by anything. Maybe that’s what you want, maybe it’s OK for your application. Personally, it makes me a bit uneasy.

You can reverse the reference:

table vehicles(id, bus_id, car_id, reg_no, ...)
table busses(id, ...)

But that’s not great either if you intend to add more vehicle types. But at least DELETE FROM busses WHERE id = ...; does what you would expect.

In my use case, I have two types of tokens: short-term sing-in PINs and non-expiring API keys. You can generalize them as a token, but from the product perspective, they are two separate things. I implemented them both on top of a single tokens table with two changeset functions.

siddhant3030

siddhant3030

What @stefanchrobot has suggested is a pretty good way to tackle this problem. We usually avoid creating different tables for this problem.
But we don’t use Ecto.Enum. We use postgres enum field for fixed values and also its much faster. @cvkmohan maybe you can take a look at that.

LostKobrakai

LostKobrakai

It’s not an either/or decision. Ecto.Enum is a runtime value, which can work with many db level setups including db level enums.

dimitarvp

dimitarvp

I would just use embedded schemas and slap polymorphic_embed on top.

thanos

thanos

We use a very similar mechanism to polymorphic_embed , but then you have some restrictions:

  1. The “child records” can only use fields valid for use in embedded schemas, i.e. no Foreign keys.
  2. When you query/aggregate against the embedded fields you will need to use postgreSql’s jsonb syntax in fragments.

So as always it’s a choice of compromises:

Using @stefanchrobot suggestion puts the mess in the schema but keeps things clean in the code and ecto expressions.
Or using @dimitarvp suggestion keeps the schema clean and can bring many of the nosql benefits to your design at the cost of query complexity, and possibly a performance hit and some restrictions to your design.
Either way good use of ecto’s changesets makes implementing choice much easier, interesting, safer and a lot of fun.

Finally there is the third choice: Use PostgreSQL inheritance, and when you are doing polymorphic querying use a case expression to prevent slicing the returned child objects.

— All posts loaded —

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
apz
I’m new to elixir and just tried to install the elixirLS extension for VScode(ium) and it is throwing some errors that I would like help ...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews