views:

34

answers:

3

Hi I am busy making a ruby on rails app.

I want to make an model that contains a text model, a picture model and a link model. Every model can have comments, But i don't want to make different comment models for the text, picture and link model. Is it possible to make a media model witch has a subclass(or how it is called) aka: picture model, text model and link model. Or is there an other clean way to do this. Thanks

A: 

You're right on track. You can have a media model that has_many comments. You can then do extends Media in your Picture, Link and Text models

corroded
A: 

You can create Comment model that has polymorphic association:

# Comment model
belongs_to :commentable, :polymorphic => true

# Other model that should has comments
has_many :comments, :as => :commentable

You can add above line to every model that needs comments. In order to have polymorphic association you need to have those columns in comments table in db:

commentable_id   - int
commentable_type - string

You can also use some plugin for comments, on example this.

klew
Is it possible to remove the commentable_type in the database (I wont use @comment.text, @comment.picture, @comment.link)?
kaibakker
@kaibakker: if you have 3 different models for text, picture and link each with its own id, then you need to have `commentable_type` because you need to know to which model this comment belongs. You can have only `comment_id` if you do it in the way @corroded proposed - so only one table in db for 3 models that inherit from `Media` model.
klew
Thanks, that was a stupid question!
kaibakker
Some questions seem to be stupid when you know the answer ;)
klew
A: 

Isn't it possible to add for evert type of media a new database table with comments, text_comment, picture_comment and link_comment. they could be made while migrating, the only problem is how do i call information from these databases?

kaibakker