理解Rails ActiveRecord"单一模型"自联接

gar*_*man 13 activerecord ruby-on-rails-3

我很难理解如何在Rails中实现单个模型自联接.在对ActiveRecord的关联部分2.10指南简要介绍了自联接,但不提供足够的信息,以及每个实例或发布这个如引用友好的朋友Railcast例子,这不是一个单一的模式自加入作为描述的Rails指南第2.10节.

这个想法是has_many和belongs_to本身的模型,不需要单独的关系表.我看到需要一个单独的表的唯一原因是,如果您希望关系包含更多信息而不仅仅是关系.例如"最好的朋友","几乎不认识他们"

我有一个简单的Post模式:

create_table "posts", :force => true do |t|
    t.datetime "posted"
    t.string   "nick"
    t.string   "title"
    t.text     "content"
    t.integer  "parent_post_id"
    t.datetime "created_at",     :null => false
    t.datetime "updated_at",     :null => false
end
Run Code Online (Sandbox Code Playgroud)

parent_post_id是对其他Post post_id的自引用.posts.rb模型具有定义的关系:

class Post < ActiveRecord::Base
  has_many :replies, :class_name => "Post"
  belongs_to :parent_post, :class_name => "Post",
    :foreign_key => "parent_post_id"
end
Run Code Online (Sandbox Code Playgroud)

在Controller或View中,我希望能够做到这样的事情:

@posts.each do |post|
  ...
  @replies = post.replies
  @replies.each do |reply|
    ...
  end
end
Run Code Online (Sandbox Code Playgroud)

或者找一个帖子的父母:

@parent_post = post.parent_post
Run Code Online (Sandbox Code Playgroud)

这可能都是一些语法错误理解.所以,提前感谢任何能够对我有所了解的人.我查看了每个SO和博客文章,没有人尝试过"指南"中描述的单一模型自引用自连接方法.

任何提供解释的人都不会指向使用单独关系表的友方朋友示例.

gar*_*man 25

我错过了"parent_post_id"的has_many外键.一旦设置,post.replies将通过parent_post_id引用其他Post实例.

posts.rb模型具有定义的关系:

class Post < ActiveRecord::Base
  has_many :replies, :class_name => "Post",
    :foreign_key => "parent_post_id"
  belongs_to :parent_post, :class_name => "Post",
    :foreign_key => "parent_post_id"
end
Run Code Online (Sandbox Code Playgroud)

我现在可以创建帖子,将parent_post_id分配给不同的帖子,然后获得回复任何父帖子的所有帖子.