Forum: Ruby on Rails making a generic comment model

Posted by eggie5 (Guest)
on 2010-03-09 02:48
(Received via mailing list)
I have a Comment model obviously to make comments. I have also a
Person and Family class and I want to make comments on bother a person
and a family. How can I set this up. I want to use the same generic
comments table for all the comments on both person and family model. I
can't figure it out, I can set up comments for either a Person or a
Family one at a time but not both.

Comment
   person_id

Class Person
   has_many :comments

How can I make comments work on the Family model too?
Posted by Daniel Guettler (dguettler)
on 2010-03-09 04:09
(Received via mailing list)
You want to make comment a polymophic association
e.g. on your person and family model you have:

has_many :comments, :as => :attachable

then on the comment class you have:

belongs_to :attachable, :polymorphic => true

and in your table for comments you have:

integer :attachable_id
string :attachable_type
text :comment

Best, Daniel
Posted by eggie5 (Guest)
on 2010-03-09 04:21
(Received via mailing list)
thanks you! polymorphic association it's called you say. It works
now.
Posted by Rick Denatale (rdenatale)
on 2010-03-09 13:50
(Received via mailing list)
On Mon, Mar 8, 2010 at 10:20 PM, eggie5 <eggie5@gmail.com> wrote:
> thanks you! polymorphic association it's called you say. It works
> now.
>

You might want to have a look at the acts_as_commentable plugin

http://github.com/jackdempsey/acts_as_commentable

It expands on this idea, but uses commentable rather than attachable
as the association name, which I think makes a bit more sense, and is
less likely to collide if you decide that one or more of the models
which can have comments can also have uploaded files as attachments.

--
Rick DeNatale

Blog: http://talklikeaduck.denhaven2.com/
Twitter: http://twitter.com/RickDeNatale
WWR: http://www.workingwithrails.com/person/9021-rick-denatale
LinkedIn: http://www.linkedin.com/in/rickdenatale
Please log in before posting. Registration is free and takes only a minute.
Existing account (Switch to SSL-encrypted connection)
NEW: Do you have a Google/GoogleMail or Yahoo account? No registration required!
Log in with Google account | Log in with Yahoo account
No account? Register here.