Reputation: 570
I know that validating by creating an index is foolproof, compared to adding the "uniqueness" keyword to a model.
Is there value in having both an index and the "uniqueness". Or would that be a bad idea?
user.rb:
validates :email, uniqueness: true
schema.rb
add_index "users", ["email"], name: "index_users_on_email", unique: true
Upvotes: 3
Views: 1398
Reputation:
Yes, there is a value in both approaches, and you want to use both. Also validation and index have different purposes.
By adding index to database, first you improve performance, and second insure that on the very low level (even if someone is trying to force duplication) you guarantied to have unique data. It does not quit validate uniqueness. Your app will throw exception if you try to insert duplicate.
Adding uniqueness in validations means that if you want to save/update something invalid, Rails will catch that and show a error message (no exceptions). You can always skip Rails validations by saving with validate: false
argument, but you will never be able to avoid uniqueness on the database level.
Upvotes: 4