# Conditional insertions to hbtm join tables

**URL:** <https://www.ruby-forum.com/t/conditional-insertions-to-hbtm-join-tables/127664>\
**Category:** Rails\
**Created:** [January 31, 2008, 6:37am UTC](https://www.ruby-forum.com/t/conditional-insertions-to-hbtm-join-tables/127664 "2008-01-31T06:37:59Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![apramanik](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/e9a140/32.png) [@apramanik](https://www.ruby-forum.com/u/apramanik)\
**Post date:** [January 31, 2008, 6:37am UTC](https://www.ruby-forum.com/t/conditional-insertions-to-hbtm-join-tables/127664/1 "2008-01-31T06:37:59Z")

</div>

Is there anyway I can prevent the collection\<\<(object, …) and similar  
methods from adding objects that do not satisfy a specific condition.  
This would be similar to the :condition option on the  
has\_and\_belongs\_to\_many association.

I want to somehow place a condition or rewrite  
collection\<\<(object, …) and similar methods so that when an  
“incompatible” object is attempted to be added to the collection, it  
returns false or throws an exception. Is this possible?

Thanks!

---

<div class="post-metadata">

**Author:** ![apramanik](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/e9a140/32.png) [@apramanik](https://www.ruby-forum.com/u/apramanik)\
**Post date:** [February 1, 2008, 9:09pm UTC](https://www.ruby-forum.com/t/conditional-insertions-to-hbtm-join-tables/127664/2 "2008-02-01T21:09:59Z")

</div>

On Jan 30, 2008 11:37 PM, apramanik [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> I want to somehow place a condition or rewrite  
> collection\<\<(object, …) and similar methods so that when an  
> “incompatible” object is attempted to be added to the collection, it  
> returns false or throws an exception. Is this possible?

Sounds like you want validates\_associated.

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

–  
Greg D.  
[http://destiney.com/](http://destiney.com/)

---

<div class="post-metadata">

**Author:** ![apramanik](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/e9a140/32.png) [@apramanik](https://www.ruby-forum.com/u/apramanik)\
**Post date:** [February 8, 2008, 8:18am UTC](https://www.ruby-forum.com/t/conditional-insertions-to-hbtm-join-tables/127664/3 "2008-02-08T08:18:38Z")

</div>

It was a condition relating the record with the association and the  
associated record.

I ended up using the :before\_add option and raising an exception  
(which rolls back the transaction).

Thanks!
