Forum: Ruby on Rails share controller/table

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Armen Arevian (Guest)
on 2009-04-16 22:29
(Received via mailing list)
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
Wisccal W. (Guest)
on 2009-04-18 15:05
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
http://api.rubyonrails.org/classes/ActiveRecord/As...
This topic is locked and can not be replied to.