Create Schemas

Learn how to create schemas.

Let’s look at the DSL Ecto provides to create schemas. We’ll use the DSL to specify the fields we want to map and their data types.

Map schema fields

Let’s start with our tracks table. We’ll have just five fields for now:

  • id, a unique ID for our track.

  • title, a string representing the track’s title.

  • duration, the length of the track in seconds.

  • index, a number representing the track’s position in an album.

  • number_of_plays, a counter that we increment every time we play the track.

If we’re writing an Elixir application that doesn’t use Ecto, we would most likely create a %Track{} struct to hold this data. We need to open a file named track.ex and add something like this:

Press + to interact
defmodule MusicDB.Track do
defstruct [:id, :title, :duration, :index, :number_of_plays]
end

With Ecto, the process is similar. Rather than defstruct, we’ll use the schema macro, and rather than a list of atoms, we’ll provide fields. With these changes, our code will look like this:

Press + to interact
defmodule MusicDB.Track do
use Ecto.Schema
schema "tracks" do
field :title, :string
field :duration, :integer
field :index, :integer
field :number_of_plays, :integer
timestamps()
end
end

What do we do?

This defines a new %Track{} ...