Hi everyone,
I have been banging my head with the following unique_constraint issue in the changeset:
My database table and index:
Table "public.invoices"
Column | Type | Modifiers
------------------+------------------------+-----------
provider_id | integer | not null
invoice_number | character varying(255) | not null
payment_order_id | integer | not null
Indexes:
"invoices_provider_id_invoice_number_index" UNIQUE, btree (provider_id, invoice_number)
My changeset:
def changeset(%PaymentOrder{} = payment_order, attrs, document) do
payment_order
|> cast(attrs, [:date, :invoice_number, :exchange_rate, :amount, :check_number, :bank_account_id])
|> validate_required([:date, :invoice_number, :exchange_rate, :amount, :check_number, :bank_account_id])
|> validate_number(:exchange_rate, greater_than: 0)
|> validate_number(:amount, greater_than: 0)
|> validate_number(:check_number, greater_than: 0)
|> validate_amount(document)
|> today_or_future_date()
|> validate_local_invoice_format()
|> add_num_year_to_changeset("payment_num_sequence")
_|> unique_constraint(:invoice_number, name: :invoices_provider_id_invoice_number_index)_
|> unique_constraint(:num, name: :payment_num_sequence_year_index)
|> unique_constraint(:check_number, name: :payment_orders_bank_account_id_check_number_index)
end
The problem:
invoice_number unique_constraint validations fails to add error to changeset and the database blows up with a constraint error.
It is very interesting that the other two unique validations work fine.
Database error:
Ecto.ConstraintError at POST /contracts/1/payment_orders
constraint error when attempting to insert struct:
* unique: invoices_provider_id_invoice_number_index
If you would like to convert this constraint into an error, please
call unique_constraint/3 in your changeset and define the proper
constraint name. The changeset has not defined any constraint.
Thanks for your help.
Best regards.