# 1 comment system for multiple models

**URL:** <https://www.ruby-forum.com/t/1-comment-system-for-multiple-models/149026>\
**Category:** Rails\
**Created:** [September 19, 2008, 2:36pm UTC](https://www.ruby-forum.com/t/1-comment-system-for-multiple-models/149026 "2008-09-19T14:36:44Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Tarscher](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/8491ac/32.png) [@Tarscher](https://www.ruby-forum.com/u/Tarscher)\
**Post date:** [September 19, 2008, 2:36pm UTC](https://www.ruby-forum.com/t/1-comment-system-for-multiple-models/149026/1 "2008-09-19T14:36:44Z")

</div>

Hi all,

I have a commenting system I use on different models (posts, reports,  
events) meaning that I have some difficulties using depend =\> destroy  
and counter cache.

I now use a sub\_id in my comment indicating whether the comment  
belongs to a post, event or report eg:  
Events table  
id | owner\_id | category\_id | text  
0 1 post …  
1 1 event …  
2 2 report …  
3 2 post …

Where the owner\_id is the id own the post, event or report.

This approach makes it hard to use either counter cache or depend =\>  
destroy since it will only look at the owner\_id. If a user deletes  
post 1 it will also delete the comments of both event 1 and report 1.

Someone has a better approach to using 1 comment system for multiple  
models or can I overwrite counter cache and depend destoy to make use  
of scoping?

All help is greatly appreciated.

Stijn

---

<div class="post-metadata">

**Author:** ![Tarscher](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/8491ac/32.png) [@Tarscher](https://www.ruby-forum.com/u/Tarscher)\
**Post date:** [September 19, 2008, 3:06pm UTC](https://www.ruby-forum.com/t/1-comment-system-for-multiple-models/149026/2 "2008-09-19T15:06:48Z")

</div>

What you want to use here are polymorphic associations.  
They work mostly like what you have done, using two  
columns, one for the id, the other for the type.  
commentable\_id  
commentable\_type  
in your case.

Then you could define associations like  
has\_many :comments, :as =\> :commentable, :dependent =\> :destroy

and Rails would be able to handle al the sub tasks as  
it does with common associations.

read the details here:

> **[ActiveRecord::Associations::ClassMethods](https://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html)**
>
> Associations are a set of macro-like class methods for tying objects together through foreign keys.

since it’s a bit too complex to explain it here
