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 ...

Get Mastering Elixir now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.