# How to Validate Uniqueness Of a Record within Date Range

**URL:** <https://www.ruby-forum.com/t/how-to-validate-uniqueness-of-a-record-within-date-range/137160>\
**Category:** Rails\
**Created:** [May 9, 2008, 4:21pm UTC](https://www.ruby-forum.com/t/how-to-validate-uniqueness-of-a-record-within-date-range/137160 "2008-05-09T16:21:51Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![ror\_arch](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/e19adc/32.png) [@ror\_arch](https://www.ruby-forum.com/u/ror_arch)\
**Post date:** [May 9, 2008, 4:21pm UTC](https://www.ruby-forum.com/t/how-to-validate-uniqueness-of-a-record-within-date-range/137160/1 "2008-05-09T16:21:51Z")

</div>

I would like to validate the uniqueness of a record within a date range.

For example : I want a customer attached to a post office within a date  
range arrives(date) and departs (date).

So this is ok:  
customer1; postoffice1; Feb1(arrives);Mar1(departs)  
customer1; postoffice1; Mar2(arrives);Apr1(departs)

This however is NOT ok:  
customer1; postoffice1; Feb1(arrives);Mar1(departs)  
customer1; postoffice1; Jan1(arrives);Feb10(departs) [xxx overlapping  
dates xxx]

The validation clause for this would be?

? validates\_uniqueness\_of :customer\_id, :scope =\>  
[:postoffice\_id,:arrives,:departs], :message=\>“This unit with this  
arrival date for this PSO already exists.”  
?

I dont think the above is right? How do I specify range within scope.

---

<div class="post-metadata">

**Author:** ![ror\_arch](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/e19adc/32.png) [@ror\_arch](https://www.ruby-forum.com/u/ror_arch)\
**Post date:** [May 9, 2008, 6:20pm UTC](https://www.ruby-forum.com/t/how-to-validate-uniqueness-of-a-record-within-date-range/137160/2 "2008-05-09T18:20:15Z")

</div>

I don’t see a way for you to combine the high-level validations to do  
what  
you want. However, you can overwrite the validate method to do what you  
want.

class SomeModel \< ActiveRecord::Base  
def validate  
#custom validation here  
end  
end

See  
[http://www.railsbrain.com/api/edge/doc/index.html?a=C00000457&name=Validations](http://www.railsbrain.com/api/edge/doc/index.html?a=C00000457&name=Validations),  
which shows an example Person model that uses the high-level  
validations  
and overwrites validate. It also shows how to add errors if your custom  
validation fails.

Regards,  
Craig
