Как использовать сложное ограничение в экто?

Это то, что я хочу реализовать

1. Customer can create a contact with name and phone number.
2. Customer can not create a contact with already existing phone number.

Так я и сделал это...

schema "people" do
    field :name, :string
    field :phone_number, :string
    belongs_to :phonebook, Phonebook

    timestamps()
  end

  def changeset(%Person{} = person, attrs) do
    person
    |> cast(attrs, [:name, :phone_number])
    |> validate_required([:name, :phone_number])
    |> unique_constraint(:phone_number])
  end

и в файле миграции

create unique_index(:people, [:phone_number)

Но другой клиент не может создать контакт с тем же номером, потому что другой клиент может иметь тот же номер. Так, каково решение для этого? Я посмотрел документ Ecto и нашел https://hexdocs.pm/ecto/Ecto.Changeset.html 1

Сложные ограничения

это правильное решение? Я попробовал это как задокументировано, но это не сработает.

1 ответ

Одним из способов является customer_id поле в схеме. Затем примените уникальное ограничение к обоим phone_number а также customer_id поле. В этом случае номер телефона будет ограничен добавленным клиентом. Когда клиент создает контакт, установите для customer_id контакта идентификатор клиента

В миграционном файле

create table(:people) do
  ...
  add :customer_id, :integer
end

create unique_index(:people, [:phone_number, :customer_id], name: :people_phone_number_customer_id_index)

В модели модуля

schema "people" do
field :name, :string
field :phone_number, :string
field :customer_id, :integer
belongs_to :phonebook, Phonebook

timestamps()

конец

def changeset(%Person{} = person, attrs) do
person
|> cast(attrs, [:name, :phone_number, :customer_id])
|> validate_required([:name, :phone_number, :customer_id])
|> unique_constraint(:phone_number, name: :people_phone_number_customer_id_index)
end
Другие вопросы по тегам