Rails - upsert 没有找到唯一索引

yu-*_*der 1 ruby activerecord ruby-on-rails

这是我的迁移文件。

  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
Run Code Online (Sandbox Code Playgroud)

这是我的代码。

BookOwners.upsert({
  book_id: 123,
  book_detail_id: 234,
  ...
}, unique_by: { columns: [:book_id, :book_detail_id] })
Run Code Online (Sandbox Code Playgroud)

但我收到此错误。

No unique index found for {:columns=>[:book_id, :book_detail_id]}
Run Code Online (Sandbox Code Playgroud)

Seb*_*lma 6

从文档:

唯一索引可以通过列或名称标识:

unique_by: :isbn
unique_by: %i[ author_id name ]
unique_by: :index_books_on_isbn

我看到您正在将哈希传递给unique_by选项,请尝试仅使用数组[:book_id, :book_detail_id]

BookOwners.upsert({
  book_id: 123,
  book_detail_id: 234,
  ...
}, unique_by: [:book_id, :book_detail_id])
Run Code Online (Sandbox Code Playgroud)