How to make ActiveRecord ThreadSafe

后端 未结 2 1301
梦毁少年i
梦毁少年i 2020-12-16 06:23

How can I make the following controller threadsafe in rails 4 with postgresql:

def controller_action
  if Model.exists(column_name:\"some_value\")
  else
            


        
2条回答
  •  春和景丽
    2020-12-16 06:56

    Contrary to the comments, concurrent inserts on the same table are entirely permissible in PostgreSQL, so there's a race condition here.

    To make this safe you must have a unique constraint (or primary key) on column_name. Duplicate inserts will then throw an exception which you can catch and retry with an update.

    If you don't have a unique constraint, then you must LOCK TABLE ... IN EXCLUSIVE MODE to prevent concurrent upserts. Or use one of the concurrency-safe methods described in:

    How to UPSERT (MERGE, INSERT ... ON DUPLICATE UPDATE) in PostgreSQL?

提交回复
热议问题