我可以写什么来修复ActiveRecord :: RecordNotUnique?

时间:2017-12-21 14:14:10

标签: ruby-on-rails activerecord rails-activerecord

我似乎无法动摇这个例外。我有以下代码:

class Batch < ApplicationRecord

  before_create :upcase_session_id     

  def self.for_session(session_id, opts)
    batch = Batch.where(session_id: session_id.upcase).first_or_initialize
    if batch.new_record?
      batch.property = opts[:property]
      batch.save!
    end
    batch
  end

  private

  def upcase_session_id
    self.session_id = session_id.upcase
  end
end

致电代码:

def retrieve_batch
    self.batch ||= Batch.for_session(batch_session_id, property: property)
end

架构批次表:

 create_table "batches", force: :cascade do |t|
    t.string   "session_id"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
    t.integer  "property_id"
    t.index ["property_id"], name: "index_batches_on_property_id", using: :btree
    t.index ["session_id"], name: "index_batches_on_session_id", unique: true, using: :btree
  end

我不确定如何更改此代码以停止获取我不断获得的此异常。

例外:

PG::UniqueViolation: ERROR: duplicate key value violates unique constraint 
"index_batches_on_session_id" DETAIL: Key (session_id)=(A19A5BFD-A90C-40B4-9384-5C6C1C88213B) already exists. : 
INSERT INTO "batches" ("session_id", "created_at", "updated_at", "property_id") 
VALUES ($1, $2, $3, $4) RETURNING "id" where my schema.rb shows:
t.index ["session_id"], name: "index_batches_on_session_id", unique: true, using: :btree 

1 个答案:

答案 0 :(得分:3)

当无法插入记录时会引发异常,因为它会违反唯一性约束。您应该告诉我们表约束,因为问题可能是任何列。

你可以试试这个:

class Batch < ApplicationRecord

  def self.for_session(session_id, opts)
    Batch.where(session_id: session_id.upcase).first_or_create(property: opts[:property])
  end

end