The Perils of Uniqueness Validations

July 17, 2013 derekprior rails SQL The Perils of Uniqueness Validations Your Rails application probably makes use of uniqueness validations in several key places. This validation provides for a nice user experience when duplicate records are detected but as we will see in a moment, is not enough to ensure data integrity. What Can Go Wrong? Let’s take a look at a our sample User class. class User validates :email, presence: true, uniqueness: true end When you persist a user instance, Rails will validate your model by running a SELECT query to see if any user records already exist with the provided email. Assuming the record proves to be valid, Rails will run the INSERT statement to persist the user. This works great in development and may even work in production if you’re running a single instance of a single process web server. But you’re not running a lone instance of WEB...