# Share controller/table

**URL:** <https://www.ruby-forum.com/t/share-controller-table/165729>\
**Category:** Rails\
**Created:** [April 16, 2009, 8:29pm UTC](https://www.ruby-forum.com/t/share-controller-table/165729 "2009-04-16T20:29:37Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Armen\_Arevian](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/5f9b8f/32.png) [@Armen\_Arevian](https://www.ruby-forum.com/u/Armen_Arevian)\
**Post date:** [April 16, 2009, 8:29pm UTC](https://www.ruby-forum.com/t/share-controller-table/165729/1 "2009-04-16T20:29:37Z")

</div>

I’m building a type of CMS and have a question about sharing code/  
tables. So i have a typical blog setup with a ‘posts’ controller  
which has many comments. I need to also make an ‘article’ controller  
which is similar to posts but different enough that it needs its own  
controller. Comments though will work exactly the same. Rather than  
remake the comments table/code (i.e. ‘article\_comments’ controller),  
i’d prefer to just share the general comments controller/table. Is  
there a way to do this?

Table schema for comments table would then be something like:

> ID  
> CommentBody  
> BelongsToType (i.e. category ‘article’, ‘post’, etc)  
> ParentID (i.e. a specific ‘articleID’, ‘postID’)

(BelongsToType column wouldnt be needed if I could make the post or  
article ID unique across both of those tables though).

Any thoughts?

Thanks so much,  
Armen

---

<div class="post-metadata">

**Author:** ![Armen\_Arevian](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/5f9b8f/32.png) [@Armen\_Arevian](https://www.ruby-forum.com/u/Armen_Arevian)\
**Post date:** [April 18, 2009, 1:05pm UTC](https://www.ruby-forum.com/t/share-controller-table/165729/2 "2009-04-18T13:05:02Z")

</div>

Armen Arevian wrote:

> I’m building a type of CMS and have a question about sharing code/  
> tables. So i have a typical blog setup with a ‘posts’ controller  
> which has many comments. I need to also make an ‘article’ controller  
> which is similar to posts but different enough that it needs its own  
> controller. Comments though will work exactly the same. Rather than  
> remake the comments table/code (i.e. ‘article\_comments’ controller),  
> i’d prefer to just share the general comments controller/table. Is  
> there a way to do this?

Hi Armen

I think you should look into polymorphic associations. Something along  
the lines of:

class Comment \< ActiveRecord::Base  
belongs\_to :attachable, :polymorphic =\> true  
end

class Post  
has\_many :comments, :as =\> :attachable  
end

class Article  
has\_many :comments, :as =\> :attachable  
end

should work.

Check out the API at

> **[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.
