Handles external data such as databases and JSON APIs

  • Repo
  • Query
  • Schema
  • Changset

Repo: communicates with external data source or database

Has common methods:

  • get(): gets the record
  • insert(): creates the record in that database
  • update()
  • delete()
  • transaction() …

Phoenix uses Repo through:

  • config.exs as config :appname, Appname.Repo,
  • repo.ex in /lib/appname/repo.ex

Common methods

Repo.update_all("tablename", set: [updated_at: Ecto.DateTime.utc])


Reusable data-model for moving data around. Schemas are a useful shortcut used in querying so you don’t have to specify all the attributes

Schema Associations

sets relationships between tables

  • has_many
  • has_one
  • belongs_to
  • many_to_many

Virtual Attributes

Disposable attributes that are not saved to the database. For example, an office address that is used to get a latitude and longitude to store in the database, without storing the office address

Embedded Schema

A schema that doesn’t use a datbase


Allows manipulation of the data to match Schema so that it can be passed to the Repo

  • Cast: filters the parameters with the attributes to be accepted into the changeset
  • Validate: validates those filtered attributes. This includes constraints which are set on the database level


def changeset(schemaname, attrs) do
  |> cast(attrs, [:key1, :key2,..])
  |> validate_required([:key1])
  |> validate_inclusion(:name, ["John", "Jack"])
  |> validate_exclusion(:name, ["Jub Jub"])
  |> validate_length(:country, is: 2)
  |> validate_length(:password, min: 8, max: 32)


attrib_name = get_field(changeset, :attrib_name)

Schemaless Changeset


model = %{key1: :string, key2: string} 
attributes = %{key1: "value", key2: "value"}    
changeset = {%{}, model}
  |> cast(attributes, Map.keys(model))
  |> validate_required([:key1])

Ecto Queries (see other article)


Phoenix Ecto

allows changeset shortcuts into forms