← All series

Series contents

Log in to track your progress

  1. 1. Ecto Overview: The Repo Episode
  2. 2. Configuring a new project with Ecto Episode
  3. 3. Creating Ecto Migrations Episode
  4. 4. Schema-less Ecto Queries Episode
  5. 5. Our first Ecto schemas Episode
  6. 6. Some useful Ecto functions Episode
  7. 7. Configuring IEx for working with Ecto Episode
  8. 8. Ecto belongs_to and has_many Episode
  9. 9. Ecto many_to_many and joining through Episode
  10. 10. Naming things in an Ecto project Episode
  11. 11. Ecto changesets: change vs cast Episode
  12. 12. Ecto changesets, validations and constraints Episode
  13. 13. Ecto build_assoc and put_assoc Episode

Our first Ecto schemas

Now that we've seen how to query the database without schemas, lets create some Ecto schemas and contrast working with them to working without them.

First, add an about field to the CreateUser migration.

defmodule Linkly.Repo.Migrations.CreateUsers do
  use Ecto.Migration

  def change do
    create table(:users) do
      add :about, :text
      add :email, :string
      add :username, :string

      timestamps()
    end

    create unique_index(:users, [:email])
    create unique_index(:users, [:username])
  end
end

Then drop and create the database with:

mix ecto.drop
mix ecto.create
mix ecto.migrate

Creating a User schema

Create a file called user.ex under lib/linkly with the following:

defmodule Linkly.User do
  use Ecto.Schema
  alias Linkly.Bookmark

  schema "users" do
    field :about
    field :email
    field :username
    has_many(:bookmarks, Bookmark)

    timestamps()
  end
end

Using the schema in IEx

third_user = %User{
  username: "sam",
  email: "sam@example.com",
  about: "I like to laugh. Haha haha..."
}

Repo.insert(%User{username: "sam", email: "sam@example.com", about: "I do not like green eggs and ham. No I don't. I don't like them one bit!"})

sam_query = from User, where: [username: "sam"]
Repo.update_all(sam_query, set: [email: "sam@gmail.com"])

Now, with the schema, we get an easier interface to work with. More examples starting at 9:20.

Open standalone page ↗

No Comments