views:

18

answers:

2

I want to create a system for users to comment on posts where comments can also have replies. Since I can't do a self-referential HABTM relationship, I did some research and saw that I should be going about it in this manner:

Post
  has_many :comments
end

Comment
  belongs_to :user
  belongs_to :post
  has_many :replies, :class_name => 'Comment'
end

I know this isn't 100% correct (which is why I'm asking). If anyone could advise me on how to set up this sort of relationship and how I would need to create the migrations, I'd appreciate it!! Thanks!

+3  A: 

The simplest solution to this is to just use the acts_as_tree plugin. It's pretty easy to see how it's implemented, but basically you need to add a self-referential belongs_to as well as a parent_id column on your model. (A comment with a nil parent_id is a top-level comment; not a reply.)

Andrew Vit
+1  A: 

Assuming it is also possible to reply to a reply, you would be having a tree of comments. Therefore I suggest you use acts_as_tree:

Comment < ActiveRecord::Base
  belongs_to :user
  belongs_to :post
  acts_as_tree :order => 'created_at'
end
captaintokyo