Preventing duplicate records across multiple connections using Rails
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.
精彩评论