开发者

Preventing duplicate records across multiple connections using Rails

开发者 https://www.devze.com 2023-02-03 21:32 出处:网络
I have two separate processes开发者_运维技巧, each with it\'s own database connection, inserting product records into a table. Before a process inserts a product into the table, it checks to see if a

I have two separate processes开发者_运维技巧, each with it's own database connection, inserting product records into a table. Before a process inserts a product into the table, it checks to see if a product with the same properties already exists. If the product already exists, the process modifies one field and saves the product. Otherwise, the process creates a new product.

I'm wrapping the find and create in a transaction, but duplicate products still get inserted because ActiveRecord transactions only act on a single database connection.

What's the best way to prevent duplicate products from being inserted across multiple database connections using ActiveRecord and Rails?


You could create a multi-field key on the table, which will enforce unique combinations of those fields. Then, your app can just watch for database INSERT errors.

0

精彩评论

暂无评论...
验证码 换一张
取 消