导轨:如何做自我指涉的has_many模型的工作? [英] Rails: How do self-referential has_many models work?
问题描述
所以,我工作的一个应用程序,我想用户能够以组对象中的文件夹。基本上是:
So, I'm working on an app where I want to users to be able to group objects in "folders". Basically:
用户的has_many:FOOS
FOOS不必是一个文件夹中,但是可以的。在这种情况下:
Foos don't have to be in a folder, but they can be. In that case:
文件夹的has_many:FOOS
和富belongs_to的:文件夹
现在,我希望能够建立文件夹,以便它们可以嵌套。我想这是一样的东西......
Now, I'd like to be able to set up folders so they can be nested. I think this is something like...
文件夹的has_many:文件夹
我听说这种自我指涉的关系,也没什么大不了的,但我真的不明白它是如何工作。我一直无法弄清楚这是怎么认为的模式和哪些列我需要提供在数据库中声明。
I have heard that this kind of self-referential relationship is no big deal, but I don't really get how it works. I haven't been able to figure out how this is supposed to be declared in the model and what columns I need to provide in the database.
任何人都可以提供一个例子吗?我也很看重任何建议/平视/警告/经验教训,你可能能够提供关于建立这种关系的一个应用程序。
Could anyone offer an example? I'd also value any suggestions/heads-up/warnings/lessons learned that you might be able to offer about setting up this kind of relationship in an app.
谢谢!
推荐答案
结帐coreyward的回答这方面的问题:<一href="http://stackoverflow.com/questions/5109303/creating-a-model-that-has-a-tree-structure">Creating一个模型,有一个树形结构
Checkout coreyward's answer to the question here: Creating a model that has a tree structure
基本上你想要一个PARENT_ID字段添加到您的文件夹表,然后建立这样在文件夹模式的关系:
Basically you want to add a "parent_id" field to your folders table and then set up a relationship in your Folder model like this:
belongs_to :parent, :class_name => "Folder"
has_many :folders, :foreign_key => "parent_id"
这篇关于导轨:如何做自我指涉的has_many模型的工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!