我正在尝试使用 ActiveRecordfind_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
失败,除了某种我无法想象的竞争条件。
(请忽略“用户”与“人”共享主键的可怕之处)
(使用 Rails 2.3.11、Postgres 9.0.3)