How can I use import to do upsert in a model that has 2 unique indexes?
lipe-pepe opened this issue · 1 comments
In my model "Students", the column 'email' has an unique index and the column 'cpf' also has an unique index. The problem is that when I try to do upsert with:
Student.import students_array, validate: true, track_validation_failures: true, on_duplicate_key_update: {conflict_target: [:email], columns: :all}
it violates the unique constraint. This error is shown:
ActiveRecord::RecordNotUnique (PG::UniqueViolation: ERROR: duplicate key value violates unique constraint "index_students_on_cpf"
DETAIL: Key (cpf)=(11223344567) already exists.
How can I solve this? I would like it to do upsert considering both cases, it email is violated or cpf is violated.
The upsert basically makes use of Postgres ON CONFLICT conditions. From what I've read this isn't really a supported scenario, but I would suggest trying to research how you would do it with SQL. My first thought is to try adding a composite unique index for both email and cpf. I can't say for sure that would work.