Unique contraints per user

2517 views elixir
8

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?

answered question

1 Answer

5

Add

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

to your migration file

posted this

Have an answer?

JD

Please login first before posting an answer.