# Validates\_uniqueness\_of with habtm

**URL:** <https://www.ruby-forum.com/t/validates-uniqueness-of-with-habtm/56860>\
**Category:** Rails\
**Created:** [April 5, 2006, 2:25am UTC](https://www.ruby-forum.com/t/validates-uniqueness-of-with-habtm/56860 "2006-04-05T02:25:16Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![lazylester](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/22d042/32.png) [@lazylester](https://www.ruby-forum.com/u/lazylester)\
**Post date:** [April 5, 2006, 2:25am UTC](https://www.ruby-forum.com/t/validates-uniqueness-of-with-habtm/56860/1 "2006-04-05T02:25:16Z")

</div>

it’s a blog…

class Entry \< ActiveRecord::Base  
has\_and\_belongs\_to\_many :categories  
end

similarly:

class Category \< ActiveRecord::Base  
has\_and\_belongs\_to\_many :entries  
end

I wish to make sure that the owner doesn’t add the same category to a  
given entry more than once… I’m thinking that validates\_uniqueness\_of  
should be usable here. But can’t figure out how to include it.

ideas?

thanks

---

<div class="post-metadata">

**Author:** ![lazylester](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/22d042/32.png) [@lazylester](https://www.ruby-forum.com/u/lazylester)\
**Post date:** [April 5, 2006, 4:09am UTC](https://www.ruby-forum.com/t/validates-uniqueness-of-with-habtm/56860/2 "2006-04-05T04:09:57Z")

</div>

Les N. wrote:

> end
> 
> I wish to make sure that the owner doesn’t add the same category to a  
> given entry more than once… I’m thinking that validates\_uniqueness\_of  
> should be usable here. But can’t figure out how to include it.
> 
> ideas?

Here’s one way…

entry.categories \<\< category unless entry.categories.include?(category)

## not sure if that’s what you’re looking for…

Bryan Buecking

---

<div class="post-metadata">

**Author:** ![lazylester](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/22d042/32.png) [@lazylester](https://www.ruby-forum.com/u/lazylester)\
**Post date:** [April 5, 2006, 4:16am UTC](https://www.ruby-forum.com/t/validates-uniqueness-of-with-habtm/56860/3 "2006-04-05T04:16:34Z")

</div>

Bryan Buecking wrote:

> Here’s one way…
> 
> entry.categories \<\< category unless entry.categories.include?(category)
> 
> ## not sure if that’s what you’re looking for…
> 
> Bryan Buecking

That’ll work well, Bryan, I had something similar but not as clean. I  
was trying to see if there was a way to use validates\_uniqueness\_of. I  
guess not though, because I’m sure you would’ve spotted it.

thanks for taking the time to help, Bryan

Les
