active_record_upsert
active_record_upsert copied to clipboard
Rails - upsert no unique index found
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]}
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