Rails:自引用 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
和 Foobelongs_to :folder
现在,我希望能够设置文件夹,以便它们可以嵌套.我认为这就像...
Now, I'd like to be able to set up folders so they can be nested. I think this is something like...
文件夹 has_many :folders
我听说这种自我参照关系没什么大不了的,但我真的不明白它是如何运作的.我一直无法弄清楚应该如何在模型中声明它以及我需要在数据库中提供哪些列.
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 对问题的回答:创建一个具有树结构的模型
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"
这篇关于Rails:自引用 has_many 模型如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!