Skip to Main Content
Mastering Elixir
book

Mastering Elixir

by André Albuquerque, Daniel Caixinha
July 2018
Intermediate to advanced content levelIntermediate to advanced
574 pages
14h 7m
English
Packt Publishing
Content preview from Mastering Elixir

Constraints

When we analyzed the User.create_changeset/2 function, we didn't have any validation in place to check whether the username we are storing in the database already exists or not. For a system like ours, this could spell trouble. As such, let's create a unique index on the users table for the username column:

$ cat apps/elixir_drip/priv/repo/migrations/20180320101722_unique_users_constraint.exsdefmodule ElixirDrip.Repo.Migrations.UniqueUsersConstraint do  use Ecto.Migration  def change do    create unique_index(:users, [:username])  endend

After we apply this migration with mix ecto.migrate, the database will start to enforce username uniqueness on any operation on the users table. Let's see what happens if we try to update the xpto_user ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Testing Elixir

Testing Elixir

Andrea Leopardi, Jeffrey Matthias

Publisher Resources

ISBN: 9781788472678Supplemental Content