# Validating the uniqueness of the combination of two fields

**URL:** <https://www.ruby-forum.com/t/validating-the-uniqueness-of-the-combination-of-two-fields/86225>\
**Category:** Rails\
**Created:** [February 20, 2007, 8:21pm UTC](https://www.ruby-forum.com/t/validating-the-uniqueness-of-the-combination-of-two-fields/86225 "2007-02-20T20:21:42Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![macarthy](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/71c47a/32.png) [@macarthy](https://www.ruby-forum.com/u/macarthy)\
**Post date:** [February 20, 2007, 8:21pm UTC](https://www.ruby-forum.com/t/validating-the-uniqueness-of-the-combination-of-two-fields/86225/1 "2007-02-20T20:21:42Z")

</div>

Is there a built-in method to validate that two fields in combination  
are unique?

e.g. if my table is :

* * *

## username | password

user1 | pass1

the following happens

MyObject.new(username=\>“user1”,password=\>“pass2”) =\> ok  
MyObject.new(username=\>“user2”,password=\>“pass1”) =\> ok  
MyObject.new(username=\>“user1”,password=\>“pass1”) =\> not ok

Thanks

---

<div class="post-metadata">

**Author:** ![macarthy](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/71c47a/32.png) [@macarthy](https://www.ruby-forum.com/u/macarthy)\
**Post date:** [February 21, 2007, 1:56am UTC](https://www.ruby-forum.com/t/validating-the-uniqueness-of-the-combination-of-two-fields/86225/2 "2007-02-21T01:56:31Z")

</div>

I am interested in this too. Does anybody have any ideas?

---

<div class="post-metadata">

**Author:** ![macarthy](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/71c47a/32.png) [@macarthy](https://www.ruby-forum.com/u/macarthy)\
**Post date:** [February 21, 2007, 2:14am UTC](https://www.ruby-forum.com/t/validating-the-uniqueness-of-the-combination-of-two-fields/86225/3 "2007-02-21T02:14:32Z")

</div>

validates\_uniqueness\_of :username, :scope =\> :password

[http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html#M000944](http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html#M000944)

(this is an extra query. You could write a unique index and rescue the  
exception).
