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.

Back to index

No Comments