【问题标题】:What can I write to fix ActiveRecord::RecordNotUnique?我可以写什么来修复 ActiveRecord::RecordNotUnique?
【发布时间】:2018-02-07 22:51:42
【问题描述】:

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

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 

【问题讨论】:

  • 你能提供你的Batch模型的代码吗?
  • 提供的信息还不够,但我可以假设:1:) session_id 在保存之前设置为 donwcase,因此在您的搜索行中,您通过session_id.upcase 搜索总是返回新的记录,并在保存行batch.session_id 保存为小写,因此引发了异常。 2:) property 有一些独特的验证需要在save! 之前检查。
  • @MikhailKatrin 我更新了上面的模型代码
  • 你遇到了什么异常?在before_create 操作中你不需要save!
  • 查看帖子标题

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


【解决方案1】:

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

你可以试试这个:

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

【讨论】:

  • 我的代码仍然出现此错误:PG::UniqueViolation: 错误:重复的键值违反了唯一约束“index_batches_on_session_id”详细信息:键 (session_id)=(A19A5BFD-A90C-40B4-9384-5C6C1C88213B ) 已经存在。 : INSERT INTO "batches" ("session_id", "created_at", "updated_at", "property_id") VALUES ($1, $2, $3, $4) RETURNING "id" where my schema.rb 显示:t.index ["session_id "],名称:"index_batches_on_session_id",唯一:true,使用::btree
  • 索引是否有可能损坏?你可以试试 REINDEX 看看能不能解决问题。
  • 不。看起来 REINDEX 没有解决问题:(
  • 你能显示数据库定义(数据库中的真实类型,除了迁移)吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多