Flatiron Labs
Published in

Flatiron Labs

How to Use Ecto.Changeset

or, be the changeset you want to see in the world

Photo by Ross Findon on Unsplash

A troublesome update scenario

Building Invoicing in Rails

Why Ecto.Changeset?

  • Ecto is a database library or "persistence framework" for Elixir. It's not the only one, but it's a nice one.
  • Ecto is two separate packages: ecto and ecto_sqlso you can get the
    data manipulation features without using a relational database.
  • You can use Ecto without Phoenix if you're building a basic Elixir app. However, it works really nicely with Phoenix, so hooray.

Building Invoicing in Elixir

Cool, and what else can changesets do?

|> cast_allowable_fields_to_their_types_as_defined_in_ecto_schema(params, [:whitelisted_field, :whitelisted_field])
|> validate_format_presence_and_everything_else_you_need()
|> handle_constraints(:field)
defmodule Registrar.Billing do
def create_invoice(attributes) do
|> Registrar.Billing.Invoice.changeset(attributes)
|> Repo.insert!()

What about constraints, though?

defmodule Registrar.Repo.Migrations.ChangeInvoicesTable do
use Ecto.Migration

def change do
create unique_index(:invoices, :email)
action: :insert,
changes: %{
email: "tracy@example.com"
errors: [
email: {"has already been taken",
constraint: :unique,
constraint_name: "email_index"
data: #Registrar.Billing.Invoice<>,
valid?: false

And can I use changesets without a schema?


Footer top
Footer bottom



We're the technology team at The Flatiron School (a WeWork company). Together, we're building a global campus for lifelong learners focused on positive impact.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store