ActiveRecord - 自引用关联
我是个 Ruby/Rails/AR 菜鸟。我有一种非常基本的数据库模式,我似乎无法找出以 Rails Way 表示的最佳方式。
Table Post
String title, author
Text content
Timestamp posted
Post parent
这里的想法是顶级帖子的父级为 NULL。每个响应都有一个父级,这样它们就形成了自然的线程。
标题、作者、内容和发布的内容我没有遇到任何问题,但家长的部分让我困惑。任何帮助、提示或建议都会很棒!
I'm a total Ruby/Rails/AR noob. I have a very basic sort of database schema that I can't seem to figure out the best way to represent in the Rails Way.
Table Post
String title, author
Text content
Timestamp posted
Post parent
The idea here is that top level posts will have parent that is NULL. Every response will have one parent, such that they form natural threads.
The title, author, content and posted I'm not having problems with but the parent bit is tripping me up. Any help, hints or suggestions would be great!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的
Post
模型应在顶部附近声明这一点:然后,使用迁移更新您的
posts
表,以便每一行都可以跟踪其父行:现在,当您有一个 < code>Post 对象称为
@post
,您可以使用@post.parent
引用其父级。Your
Post
model should declare this near the top:Then, using a migration, update your
posts
table so that each row can track its parent:Now, when you have a
Post
object called@post
, you can reference its parent with@post.parent
.看一下
act_as_tree
插件,它提供了一堆方法为您管理关系。 Railscasts 有一个关于基于树的导航的截屏视频,值得观看。Take a look at the
act_as_tree
plugin, it provides a bunch of methods that manage the relationships for you. Railscasts has a screencast on Tree Based Navigation that's worth watching.