问题描述
我很难理解如何在Rails中实现单个模型自联接."ActiveRecord关联指南"部分2.10 简要说明了自助加入",但没有提供足够的信息,并且每个示例或与此相关的示例均引用了不是单个模型自联接的Friendly Friend Railcast示例,如《铁路指南》第2.10节.
I'm having a hard time understanding how to implement a single model self-join in Rails. The Guide to ActiveRecord Associations section 2.10 briefly explains Self-Joins but doesn't offer enough information, and every example or post about this such references the Friendly Friend Railcast example that isn't a single model self join, as described in the Rails Guide section 2.10.
这个想法是一个具有has_many和belongs_to本身的模型,不需要为关系建立单独的表.我看到需要一个单独的表的唯一原因是,您是否希望该关系包含比该关系更多的信息.例如最好的朋友",几乎不认识他们"
The idea is a model that has_many and belongs_to itself, without needing a separate table for the relationship. The only reason I see for needing a separate table is if you want the relationship to contain more information than just the relationship. e.g. "best friends", "barely know them"
我有一个简单的Post模式:
I have a simple Post schema:
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
parent_post_id是对其他Post post_id的自引用.posts.rb模型具有定义的关系:
The parent_post_id is a self-reference to other Post post_id's. The posts.rb model has the relationship defined:
class Post < ActiveRecord::Base
has_many :replies, :class_name => "Post"
belongs_to :parent_post, :class_name => "Post",
:foreign_key => "parent_post_id"
end
在Controller或View中,我希望能够执行以下操作:
In the Controller or View I'm hoping to be able to do something like this:
@posts.each do |post|
...
@replies = post.replies
@replies.each do |reply|
...
end
end
或找到帖子的父级:
@parent_post = post.parent_post
这可能是一些语法误解.因此,在此先感谢任何可以对我有所了解的人.我浏览了所有SO和博客文章,没有人尝试使用《指南》中介绍的单一模型自引用自联接方法.
This may all be some syntax mis-understanding. So thanks in advance to anyone who can slap some sense into me. I've looked through every SO and blog post out there and none try the single model self-referential self-join method described in the Guide.
为任何提供解释而未指向使用单独关系表的友好朋友"示例的人提供积分.
Points for anyone offering an explanation that doesn't point to the Friendly Friend example that uses a separate relationship table.
推荐答案
我缺少"parent_post_id"的has_many外键.设置好后,post.replies将通过parent_post_id引用其他Post实例.
I was missing the has_many foreign key to "parent_post_id". Once its set, the post.replies will reference other Post instances by parent_post_id.
posts.rb模型具有定义的关系:
The posts.rb model has the relationship defined:
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
我现在可以创建帖子,为另一个帖子分配一个parent_post_id,然后再获取所有对任何父帖子进行回复的帖子.
I can now create Posts, assign a parent_post_id to a different Post, then later get all Posts that are replies to any parent Post.
这篇关于了解Rails ActiveRecord的“单一模型"自我加入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!