PaleWatcher
How do you model different ‘types’ with totally different fields in Ecto?
I’m trying to model something in Ecto where records share a few common fields, but depending on a type, they have completely different additional fields.
Roughly:
- there’s an
itemstable with the common stuff (type,same_field, etc.) - and then separate tables for each type (
items_a,items_b) - these subtype tables use the same
idas the parent (so 1:1, PK = FK)
So everything is still one logical collection, just split across tables to avoid a lot of nullable columns and to keep proper DB constraints.
In Ecto I’m using has_one + cast_assoc, and dispatching based on the type.
I’m wondering:
- does this approach fit well with Ecto, or is it something people generally avoid?
- is there a more idiomatic way to solve this without collapsing everything into one table or using JSON?
- are there any gotchas with this setup (especially around inserts or preloading)?
Example changeset:
def changeset(item, attrs) do
item
|> cast(attrs, [:type, :category, :owner_id])
|> validate_required([:type, :category, :owner_id])
|> cast_subtype()
end
The whole idea is to keep validation at the database level as much as possible, not just in changesets.
Most Liked
LostKobrakai
I recently read a good blog post on this:
This is about the plain db level. Once you have that you can add the schemas for that.
You likely want to have another layer of this eventually, which can map between [ItemA, ItemB] to those lower level nested schemas.
krasenyp
Then there’s no time to refactor the database schema. I always encourage people to not half-ass the database design. Do it properly from the get go. It’s like in sports. If you lack the fundamentals, it’s very hard to compensate afterwards.
Schultzer
Whats easy in SQL are hard in Ecto.
Thats why I’m building GitHub - elixir-dbvisor/sql: SQL provides state-of-the-art, high-performance SQL integration for Elixir, built to handle extreme concurrency with unmatched expressiveness and ergonomic query composition. Write safe, composable, parameterized queries directly, without translating to Ecto or any ORM. · GitHub to make it easy both places.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #hex









