14

I have a model that has two fields, which I will call first_name and last_name, and I want to make sure that the combination of the two are case-insensitively unique. I've gotten halfway there by using this:

validates_uniqueness_of :first_name, :scope => :last_name

The problem is that the uniqueness check seems to be case sensitive, even though the documentation says it should be case insensitive by default. So given an existing record:

{ :first_name => 'John', :last_name => 'Smith' }

This will be allowed:

{ :first_name => 'JOHN', :last_name => 'SMITH' }

As well as any additional record where there is any variation of case in either the first or last name. Why are these records being allowed? How can I enforce case insensitive uniqueness across both fields together?

Jimmy
  • 35,686
  • 13
  • 80
  • 98

1 Answers1

21

Did you try validates_uniqueness_of :first_name, :scope => :last_name, :case_sensitive => false?

The documentation says it's true by default.

(I think the link you gave is to some outdated documentation. IIRC, the default for this did change in the last couple of years.)

Luke Francl
  • 31,028
  • 18
  • 69
  • 91
  • You're right! I was mislead by the documentation I found. Setting `:case_sensitive => false` made it work for the first_name, but it doesn't work the other direction. It will still accept `{ :first_name => 'John', :last_name => 'SMITH' }`. Is there a way to make it work bi-directionally? Would I just include two `validates_uniqueness_of` rules with the field swapped? – Jimmy Feb 07 '10 at 00:00
  • I tried adding another validation with the two fields swapped. It will now catch cases where one of the fields is differently cased, but not if both are, so this still gets through: `{ :first_name => 'JOHN', :last_name => 'SMITH' }`. – Jimmy Feb 07 '10 at 00:10
  • 1
    I'd just write a custom validation method at this point if I were you. – Luke Francl Feb 07 '10 at 00:26
  • Yep, that's what I ended up doing. Thanks all. – Jimmy Feb 07 '10 at 01:45
  • 1
    You should share your custom validation method for others to learn. :) – Matt Huggins May 04 '11 at 22:14
  • 3
    https://github.com/jimmycuadra/morethingsneed.to/blob/67968671b9328d16628efad6793a5ddb5141807c/app/models/entry.rb#L54 – Jimmy May 15 '13 at 13:01