【发布时间】:2011-05-06 21:48:05
【问题描述】:
我正在尝试使用 ActiveRecord 的 find_or_create_by_*column*,但我收到来自 Postgres 的错误,让我知道它有时无法找到模型,并且无论如何都会尝试插入一个模型。保持这个表的唯一性非常重要,所以我在它的迁移中添加了一个:unique => true 属性,这样 Postgres 就会知道我是认真的。
然后,失败:
ActiveRecord::StatementInvalid: PGError: ERROR: duplicate key value violates unique constraint "index_marketo_leads_on_person_id" DETAIL: Key (person_id)=(9968932) already exists. : INSERT INTO "marketo_leads" ("mkt_person_id", "synced_at", "person_updated_at", "person_id") VALUES(NULL, NULL, '2011-05-06 12:57:02.447018', 9968932) RETURNING "id"
我有这样的模型:
class User < AR::Base
has_one :marketo_lead
before_save :update_marketo_lead
def update_marketo_lead
if marketo_lead
if (User.marketo_columns & self.changes.keys).any?
marketo_lead.touch(:person_updated_at)
end
elsif self.id
marketo_lead = MarketoLead.find_or_create_by_person_id(:person_updated_at => Time.now, :person_id => self.id)
end
end
end
class MarketoLead
belongs_to :user, :foreign_key => 'person_id'
end
第二种模型用于将我们的用户帐户链接到 Marketo 电子邮件服务器,并记录用户的某些字段上次修改的时间,以便我们可以在批处理后台任务中推送更改的记录。
除了某种我无法想象的竞争条件之外,我想不出任何原因导致此回调 update_marketo_lead 失败。
(请忽略 'user' 与 'person' 共享主键的可怕性) (使用 Rails 2.3.11,Postgres 9.0.3)
【问题讨论】:
标签: ruby-on-rails activerecord callback