Sometimes users like to double click, sometimes requests just happen very, very, very close together. This can mean that Rails isn't quick enough to use the validations you have setup in your models to prevent duplicate entries getting into the database. I've found ajax requests are particularly vulnerable.
So like all good programmers the database is setup with unique indexes and the like to ensure that, regardless of the client connecting to the database, your data stays clean.
However, this can sometimes cause annoying Duplicate entry exceptions that actually, you don't really care about and you'd just wish your application silently captured them.
A few times now I've implemented code like this...
begin
SomeObject.create(...)
rescue ActiveRecord::StatementInvalid => e
raise e unless /#{DUPLICATE_ENTRY_ERROR}/.match(e)
end
Then in an intializer I have...
DUPLICATE_ENTRY_ERROR = "Mysql::Error: Duplicate entry"
I don't like it but it does work. Another option could be to use javascript to disable form buttons after the initial submit but this felt like a more 'fool proof' method.
I'm all up for hearing any alternative suggestions, so if you know a better solution please leave a comment.
About Paul
Paul works for Kyan web design agency in Surrey, UK as a Ruby on Rails developer.
Follow Paul on Twitter
Email: paulsturgess [at] gmail.com
Got something to say?