开发者

Trying to make comments of comments. How to arrange models?

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.int开发者_如何学编程eger   :comment_id

      t.timestamps
    end
  end

  def self.down
    drop_table :comments
  end
end


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜