1

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
user1175969
  • 540
  • 6
  • 19
  • I do not really understand what you are asking. Can you explain a bit more in depth and perhaps post some code relating to what you are asking? – ruby_newbie Jun 21 '16 at 22:47
  • Sure, I just added some sample code. I basically described 2 approaches to validate uniqueness. My question is there's any benefit in using both approaches. – user1175969 Jun 21 '16 at 22:59

1 Answers1

3

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.

  • Great. Thanks! Do you know how I can validate uniqueness for a pair of columns (without using indices)? So that I can catch the error and show an error message... – user1175969 Jun 21 '16 at 23:29
  • 1
    Yes, validate with scope. Find more here: http://stackoverflow.com/questions/4870961/rails-validate-uniqueness-of-multiple-columns –  Jun 21 '16 at 23:32