active_record_upsert icon indicating copy to clipboard operation
active_record_upsert copied to clipboard

Rails - upsert no unique index found

Open wowremywang opened this issue 5 years ago • 1 comments

This is my migration file.

def change
    add_index :book_owners, [:book_id, :book_detail_id], unique: true, where: 'book_id IS NOT NULL and book_detail_id IS NOT NULL'
  end

This is my code.

BookOwners.upsert({
  book_id: 123,
  book_detail_id: 234,
  ...
}, unique_by: { columns: [:book_id, :book_detail_id] })

But I am getting this error.

No unique index found for {:columns=>[:book_id, :book_detail_id]}

wowremywang avatar Dec 24 '19 18:12 wowremywang

I think you just pass the array of fields , not a hash of them. So: unique_by: [:book_id, :book_detail_id] which looks for a unique set of book_id and book_detail_id. (no idea what happens in one of those is null) hope that helps

jcquarto avatar Aug 23 '20 21:08 jcquarto