ruby on rails 3 - First_or_create yet ERROR: duplicate key value violates unique constraint -


i have following code:

rating = user.recipe_ratings.where(:recipe_id => recipe.id).where(:delivery_id => delivery.id).first_or_create 

yet somehow occasional pg::error: error: duplicate key value violates unique constraint errors this. can't think of reason should happen, since whole point of first_or_create prevent those.

is crazy race-condition? how can solve without maddening series of begin...rescue blocks?

this seems stem typical race condition "select or insert" case.

ruby seems choose performance on safety in implementation. quoting "ruby on rails guides":

the first_or_create method checks whether first returns nil or not. if return nil, create called.

...

the sql generated method looks this:

select * clients (clients.first_name = 'andy') limit 1 begin insert clients (created_at, first_name, locked, orders_count, updated_at) values ('2011-08-30 05:22:57', 'andy', 0, null, '2011-08-30 05:22:57') commit 

if that's actual implementation (?), seems completely open race conditions. transaction can select between first transaction's select , insert. , try own insert, raise error reported, since first transaction has inserted row in meantime.

the time frame race condition drastically reduced data-modifying cte. safe version not cost more. guess have reasons.
compare safe implementation:


Comments

Popular posts from this blog

java - How to specify maven bin in eclipse maven plugin? -

single sign on - Logging into Plone site with credentials passed through HTTP -

php - Why does AJAX not process login form? -