For anyone creating a database whether through Rails or any other language, ensuring that there are no duplicates is extremely important. Imagine signing up for a service using a username, and learning later on that another user also has the same username. Not only would this be confusing and concerning for the user, but this could (and more than likely would) prevent a myriad of problems for your database.

If you have ever created a database through rails, you have more than likely used the Active Record helper uniqueness to check if an attribute is unique before saving it to the database like so:

class Account < ApplicationRecord
 validates :email, uniqueness: true
end

So what is the uniqueness helper doing for us under the hood? Uniqueness makes a SELECT SQL query to that model’s table to find if the attribute already exists, if it does not exist, it will run INSERT and persist the new instance into the database; if it does exist, however, the instance will not persist.

#sql #web-development #database #rails #preventing duplicates in databases while using rails #prevent duplicated database

Preventing Duplicates in Databases while using Rails
1.25 GEEK