Using this validation method in conjunction with ActiveRecord::Base#save does not guarantee the absence of duplicate record insertions, because uniqueness checks on the application level are inherently prone to race conditions. For example, suppose that two users try to post a Comment at the same time, and a Comment‘s title must be unique. At the database-level, the actions performed by these users could be interleaved in the following manner:
User 1 | User 2 ------------------------------------+-------------------------------------- # User 1 checks whether there's | # already a comment with the title | # 'My Post'. This is not the case. | SELECT * FROM comments | WHERE title = 'My Post' | | | # User 2 does the same thing and also | # infers that his title is unique. | SELECT * FROM comments | WHERE title = 'My Post' | # User 1 inserts his comment. | INSERT INTO comments | (title, content) VALUES | ('My Post', 'hi!') | | | # User 2 does the same thing. | INSERT INTO comments | (title, content) VALUES | ('My Post', 'hello!') | | # ^^^^^^ | # Boom! We now have a duplicate | # title!
Something to watch out for as you scale or build out your Rails app. This is the kind of stuff that only bites you when you get bigger.