Make a unique index in the database, and write this:
rescue Exception => e
# interrogate e to determine what sort of failure it was
# and take the appropriate action.
This is the right way to do this. Testing before insert doesn't
work because it's possible that after you test, but before you
insert, another process may have inserted a duplicate!