【发布时间】: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