# Avoiding duplicate inserts?

**URL:** <https://www.ruby-forum.com/t/avoiding-duplicate-inserts/135817>\
**Category:** Rails\
**Created:** [April 25, 2008, 9:23am UTC](https://www.ruby-forum.com/t/avoiding-duplicate-inserts/135817 "2008-04-25T09:23:16Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Mike\_Champion](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/8edcca/32.png) [@Mike\_Champion](https://www.ruby-forum.com/u/Mike_Champion)\
**Post date:** [April 25, 2008, 9:23am UTC](https://www.ruby-forum.com/t/avoiding-duplicate-inserts/135817/1 "2008-04-25T09:23:16Z")

</div>

I’m wondering if there is a good Rails solution to avoiding duplicate  
inserts with identical content. I know of the locking to prevent  
updates, but looking for something on inserts.

For example, say you have an API to a blog system that lets a caller  
post a comment. The client calls “addComment” with the same parameters  
(say, user\_id and comment) twice and each request is handled by a  
different mongrel instance. How can the duplicate comment be prevented  
from being saved? They would be different rows, and I would like to  
avoid table locking. (In this example, the client can’t be controlled,  
so it needs to be server-side.)

I believe that a validating on before\_save is not enough because there  
would still be a window between the validation completing and writing  
the row since it is only the row that is locked.

Any suggestions would be appreciated.

Thanks,

-mike

---

<div class="post-metadata">

**Author:** ![Mike\_Champion](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/8edcca/32.png) [@Mike\_Champion](https://www.ruby-forum.com/u/Mike_Champion)\
**Post date:** [April 25, 2008, 10:59am UTC](https://www.ruby-forum.com/t/avoiding-duplicate-inserts/135817/2 "2008-04-25T10:59:45Z")

</div>

not sure if that would work in your case, but what about unique keys in  
your database?

---

<div class="post-metadata">

**Author:** ![Mike\_Champion](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/8edcca/32.png) [@Mike\_Champion](https://www.ruby-forum.com/u/Mike_Champion)\
**Post date:** [April 25, 2008, 2:45pm UTC](https://www.ruby-forum.com/t/avoiding-duplicate-inserts/135817/3 "2008-04-25T14:45:22Z")

</div>

Sounds like a job for validates\_uniqueness\_of :comment, :scope=\>:user

The double-submit issue is a matter to solve on the client (e.g.,  
disable the submit button after it’s clicked; clear the comment field,  
etc).

For now, I’d recommend that you take this simple approach and let the  
real users’ use demonstrate that more needs to be done. I suspect  
you’re concern (beyond this) is more theoretical than practical.

On Apr 25, 4:59 am, Thorsten M. \<rails-mailing-l…@andreas-
