Search⌘ K

Create Embedded Schemas

Explore creating embedded schemas in Ecto to model nested data relationships within Elixir applications. Understand how to define embeds_one and embeds_many, use UUID primary keys, handle JSON storage, and fetch embedded records efficiently. This lesson equips you to manage embedded artist and track data within an album schema without associations.

Create new schemas

To try out embeds, we’ll move away slightly from the data model we’ve worked with so far and create a new Album schema. This one will use embeds, rather than associations, to handle the child records for Artist and Track. The relationships will still be the same—that is, albums will have one artist and have many tracks—but we’ll model these relationships using embeds.

We’ll create new schemas with different names to keep this approach distinct in our codebase. Let’s start with tracks.

We define embeds similarly to normal schemas, but we don’t provide a name for the source table since they belong to no particular table.

Elixir
defmodule MusicDB.TrackEmbed do
import Ecto.Changeset
use Ecto.Schema
embedded_schema do
field(:title, :string)
field(:duration, :integer)
end
end

Default type for the primary key

Another difference is that the default type for the primary key is binary_id ...