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?


struct_or_map_of_data
|> 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)
Repo.insert(changeset)
Repo.update(changeset)
defmodule Registrar.Billing do
def create_invoice(attributes) do
%Invoice{}
|> Registrar.Billing.Invoice.changeset(attributes)
|> Repo.insert!()
end
end

What about constraints, though?

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

def change do
create unique_index(:invoices, :email)
end
end
{:error,
#Ecto.Changeset<
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?

Resources

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