ActiveRecord validates_uniqueness_of is vulnerable to race conditions . To truly ensure uniqueness, extra precautions are needed. One of the suggestions from RDocs ActiveRecord is to create a unique index in the database, for example, by including in its migrations:
add_index :recipes, :name, :unique => true
This ensures at the database level that the name is unique. But the disadvantage of this approach is that the ActiveRecord::StatementInvalid exception that is returned when trying to save a duplicate is not very useful. You cannot be sure that you will understand this exception, that the error was generated by a double copy, and not just broken SQL.
One solution, as suggested by RDocs, is to parse the message that comes with the exception and try to find words such as "duplicate" or "unique," but this is kludgy, and the message is database specific. For SqlLite3, I understand that the message is completely general and cannot be analyzed this way at all.
Given that this is a major issue for ActiveRecord users, it would be nice to know if there is any standard approach to handling these exceptions. I will offer my suggestion below; comment or provide alternatives; thanks!
database ruby-on-rails activerecord exception indexing
Chinasaur
source share