Reputation: 1101
Ive got a question regarding the validation of uniqueness.
From : http://guides.rubyonrails.org/active_record_validations_callbacks.html#uniqueness
"It does not create a uniqueness constraint in the database, so it may happen that two different database connections create two records with the same value for a column that you intend to be unique. To avoid that, you must create a unique index in your database."
Does that mean whenever I validate uniqueness I have to add an index in the database? Or is this only necessary when its likely to happen that two recors are going to be inserted at the same time?
Whats the best practice here: Unique and Index always together or dependant on the situation?
Upvotes: 3
Views: 264
Reputation: 8131
It is essentially a race condition. In that Alice signs up with the email address [email protected] and hits the submit button twice. Because she hit them so quickly, she's only has them in memory, and they pass validation. Then both are written to the database. The solution to this is to require the database to check for uniqueness as well between the time they are stored in memory or written to the database.
What you need to do is add a line like this to the migration:
add_index :table_name, :column_name, unique: true
As far as best practices, you for sure want to do it when having two of the same would cause issues. It's probably not a huge deal if two tweets are submitted with the same content, but if you have two users with the same email address, that becomes a problem.
Upvotes: 5