views:

31

answers:

1

My :post model is the parent model. Within a post are many comments. And comments have potential of having many more comments, and so forth. I thought I had had this right, but I were to type :

Comment.last.comments 

I get :

NoMethodError: undefined method `comments' for #<Comment:0x1053a1ff0>

My Models :

#comment.rb

belongs_to  :post
belongs_to  :parent, :class_name => 'Comment'
has_many    :children, :class_name => 'Comment'

validates_presence_of :text

#post.rb

has_many                      :comments                                        
accepts_nested_attributes_for :comments, :allow_destroy => true

My Migration

class CreateComments < ActiveRecord::Migration
  def self.up
    create_table :comments do |t|
      t.text      :text
      t.integer   :post_id
      t.integer   :comment_id

      t.timestamps
    end
  end

  def self.down
    drop_table :comments
  end
end
+1  A: 

Comments does not have many comments, only many children:

Comment.last.children Moreover, you need to say what foreign key to use. Take a look on a self referenced records - http://blog.hasmanythrough.com/2006/4/21/self-referential-through Or better use trees like nested set.

c0r0ner
+1 for nested set -- see here: http://github.com/collectiveidea/awesome_nested_set
zetetic
Thanks guys. @zetetic, I'm intimidated by a plugin because of its verbosity. But I found Ryan Bates struck again with this one : http://railscasts.com/episodes/163-self-referential-association . Looks like its a reference to C0r0ner's suggestion. Thanks
Trip
Thats right. Aware that selecting all children of some comment with unlimited depth will be real pain. So if you do need unlimited comment nesting use nested set in spite verbosity
c0r0ner