Skip to content

Commit ec357ca

Browse files
committed
Validate uniqueness on (type, value) columns of the contacts table
1 parent d58b8ff commit ec357ca

File tree

2 files changed

+10
-0
lines changed

2 files changed

+10
-0
lines changed

lib/blog/accounts/contact.ex

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ defmodule Blog.Accounts.Contact do
2424
contact
2525
|> cast(attrs, [:type, :value])
2626
|> validate_required([:type, :value])
27+
|> unique_constraint(:value, name: :contacts_type_value_index)
2728
end
2829

2930
end

test/blog/accounts/accounts_test.exs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,4 +15,13 @@ defmodule Blog.AccountsTest do
1515
assert {:error, %Ecto.Changeset{}} = Accounts.create_user(attrs)
1616
assert ^contact_count = Repo.aggregate(Accounts.Contact, :count, :id)
1717
end
18+
19+
test "create_user/1 discards duplicate contacts" do
20+
contact = %{type: "phone", value: "+1 000 000 0000"}
21+
22+
assert {:ok, _} = Accounts.create_user(%{contact: contact, name: "name", password: "password"})
23+
24+
assert {:error, changeset} = Accounts.create_user(%{contact: contact, name: "other", password: "password"})
25+
assert "has already been taken" in errors_on(changeset).value
26+
end
1827
end

0 commit comments

Comments
 (0)