Search code examples
elixirphoenix-frameworkectounique-constraint

Unique contraints per user


Consider the following changeset:

defmodule Flashcards.Cards.Deck do
  use Ecto.Schema
  import Ecto.Changeset


  schema "decks" do
    field :name, :string
    field :user_id, :id

    timestamps()
  end

  @doc false
  def changeset(deck, attrs) do
    deck
    |> cast(attrs, [:name, :user_id])
    |> validate_required([:name])
    |> unique_constraint(:name)
  end
end

The unique_constraint (along with the unique_index in the migration) makes the name field unique across all users.

In practice, however, I want to make the name field unique per user - what is the best way to go about this?


Solution

  • Add

    create index(:decks, [:user_id, :name], unique: true)
    

    to your migration file