# User-friendly unique records

**URL:** <https://www.ruby-forum.com/t/user-friendly-unique-records/106045>\
**Category:** Rails\
**Created:** [June 5, 2007, 10:14pm UTC](https://www.ruby-forum.com/t/user-friendly-unique-records/106045 "2007-06-05T22:14:04Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Tyler\_MacDonald](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/b5ac83/32.png) [@Tyler\_MacDonald](https://www.ruby-forum.com/u/Tyler_MacDonald)\
**Post date:** [June 5, 2007, 10:14pm UTC](https://www.ruby-forum.com/t/user-friendly-unique-records/106045/1 "2007-06-05T22:14:04Z")

</div>

Hey everybody,

I’ve got a table that contains addresses. Addresses belong\_to users.

When a new address is added, I would like to avoid duplicates. The  
model  
should check to see if it is exactly the same as an existing address,  
and if  
it is, instead of saving the address and returning a new record, I would  
like it to load the old record.

I’m thinking something like this:

def save  
if old\_record = this\_is\_a\_duplicate\_record  
this.id = old\_record.id  
this.reload  
else  
super  
end  
end

… is this the way to do it? Or is there a better/safer method?

Thanks,  
Tyler

---

<div class="post-metadata">

**Author:** ![Tyler\_MacDonald](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/b5ac83/32.png) [@Tyler\_MacDonald](https://www.ruby-forum.com/u/Tyler_MacDonald)\
**Post date:** [June 6, 2007, 12:06am UTC](https://www.ruby-forum.com/t/user-friendly-unique-records/106045/2 "2007-06-06T00:06:23Z")

</div>

Personally, I think that’s a bad idea. Overriding the behavior of  
save seems rather dangerous and confusing. The save method should  
either return true or false (indicating validation or database errors  
encountered during save). It should not attempt to return an instance  
of some other object.

Instead you should allow the normal validation system to provide  
feedback to the user that they are attempting to insert a duplicate  
address.

I’m thinking something like:

Address \< ActiveRecord::Base  
belongs\_to :user

validate\_uniqueness\_of :address, :scope =\>  
[:user\_id, :city, :state, :zip]  
validate\_uniqueness\_of :city, :scope =\>  
[:user\_id, :address, :state, :zip]  
validate\_uniqueness\_of :state, :scope =\>  
[:user\_id, :address, :city, :zip]  
validate\_uniqueness\_of :zip, :scope =\>  
[:user\_id, :address, :city, :state]  
end

Now in your controller/view you could then provide them a link or  
possibly redirect to some view of the user showing the existing  
address. But, this type of thing should not happen anywhere in the  
model layer.
