My site has news entries, it has a party calendar and it has a blog.
Now I’d like to create a commenting system that in fact is quite simple,
but I wanna use it for all these 3 types of content.
My question: how can I do that? I maybe could add an association to all
three types in the comment model:
class Comment < ActiveRecord::Base
And in all the three models I then added a “has_many :comments”
statement. This would work, but every comment entry would belong only to
one of the three models, so there were many NULL values that seem
incorrect to me.
And when another content type would be created (like party_report) I
would have to update the comment model and it would get more and more
xxx_id fields and NULL values.
Do you see a better way for doing this? I’m still looking for a “clean”
way, but I can’t really find one using the Rails stuff I know.
My idea is something like having another attribute in the comment model
that specifies the sort of content (model) it is associated with:
create_table :comments do |t|
t.column “subject”, :string, :null => false
t.column “body”, :text, :null => false
t.column “model_type_id”, :integer, :null => false
t.column “model_type”, :varchar, :null => false
Then the data rows could look like these:
This item is associated with news_item ID = 1
subject: “this is a comment”
body: “and this is its content”
This item is associated with news_item ID = 2
subject: “this is another comment”
body: “and this is another content”
This item is associated with party ID = 5
subject: “this is yet another comment”
body: “and this is yet another content”
This item is associated with blog ID = 99
subject: “this is a blog comment”
body: “and this is a blog comment content”
Do you see what I mean? Wouldn’t this be beautiful? If I wanted to add
the party_report to it I only had to add the statement “belongs_to
:party_report” to the comment model and “has_many :comments” to the
party_report model and then I could begin adding comments without having
to change anything in the database table!
This item is associated with party_report ID = 421
subject: “yeah great party”
body: “blah blah blah”
Is there some way to achieve this? This would be REALLY GREAT! And Rails
is called “great”, so I’m looking forward!