# Callback when objects connect as a habtm relationship

**URL:** <https://www.ruby-forum.com/t/callback-when-objects-connect-as-a-habtm-relationship/155772>\
**Category:** Rails\
**Created:** [December 16, 2008, 4:46pm UTC](https://www.ruby-forum.com/t/callback-when-objects-connect-as-a-habtm-relationship/155772 "2008-12-16T16:46:19Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Kazim\_Z](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/f08c70/32.png) [@Kazim\_Z](https://www.ruby-forum.com/u/Kazim_Z)\
**Post date:** [December 16, 2008, 4:46pm UTC](https://www.ruby-forum.com/t/callback-when-objects-connect-as-a-habtm-relationship/155772/1 "2008-12-16T16:46:19Z")

</div>

If Product and Category models are in a habtm relationship, i.e.

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

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

I want a piece of code to be executed every time a product is connected  
to a  
category.  
Where do I put this code? Which callback (and on which model) will be  
triggered?

Any hints appreciated. Thanks for help.

–

- Kazim Z.  
Blog: [http://tuxplayground.blogspot.com](http://tuxplayground.blogspot.com)

---

<div class="post-metadata">

**Author:** ![Kazim\_Z](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/f08c70/32.png) [@Kazim\_Z](https://www.ruby-forum.com/u/Kazim_Z)\
**Post date:** [December 18, 2008, 3:00am UTC](https://www.ruby-forum.com/t/callback-when-objects-connect-as-a-habtm-relationship/155772/2 "2008-12-18T03:00:04Z")

</div>

Kazim Z. wrote:

> I want a piece of code to be executed every time a product is connected  
> to a category.  
> Where do I put this code? Which callback (and on which model) will be  
> triggered?

Look into adding :after\_add callbacks to the associations:

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

–  
Rails Wheels - Find Plugins, List & Sell Plugins -  
[http://railswheels.com](http://railswheels.com)
