I try to use ActiveRecord find_or_create_by_*column* , but I get errors from Postgres letting me know that it sometimes does not find the model and tries to insert it anyway. It is very important that this table is unique, so I added the attribute :unique => true to transfer it so that Postgres knows that I am serious about this.
And, a failure:
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"
I have such models:
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
The second model is used to link our user accounts to the Marketo email server and save the last time records when certain user fields were changed so that we can move the changed records in batch background tasks.
I canβt think of any reason for this callback, update_marketo_lead to fail, except for some kind of racing condition that I cannot imagine.
(please ignore the horror of the βuserβ using the primary key with the βmanβ) (using Rails 2.3.11, Postgres 9.0.3)
source share