Rails:自引用 has_many 模型如何工作?

发布于 2024-10-19 05:56:45 字数 447 浏览 6 评论 0原文

因此,我正在开发一个应用程序,我希望用户能够将对象分组到“文件夹”中。基本上:

User has_many :foos

Foos 不必位于文件夹中,但它们可以位于文件夹中。在这种情况下:

Folder has_many :foosFooBelongs_to :folder

现在,我希望能够设置文件夹,以便它们可以嵌套。我认为这就像...

Folder has_many :folders

我听说这种自我引用关系没什么大不了的,但我不太明白它是如何工作的。我无法弄清楚如何在模型中声明它以及我需要在数据库中提供哪些列。

有人能举个例子吗?我也很重视您可能能够提供的有关在应用程序中建立这种关系的任何建议/提醒/警告/经验教训。

谢谢!

So, I'm working on an app where I want to users to be able to group objects in "folders". Basically:

User has_many :foos

Foos don't have to be in a folder, but they can be. In that case:

Folder has_many :foos and Foo belongs_to :folder

Now, I'd like to be able to set up folders so they can be nested. I think this is something like...

Folder 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.

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

§对你不离不弃 2024-10-26 05:56:45

在此处查看 coreyward 对问题的回答:创建具有树结构的模型基本上

,您想要将“parent_id”字段添加到文件夹表中,然后在文件夹模型中设置关系,如下所示:

belongs_to :parent, :class_name => "Folder"
has_many :folders, :foreign_key => "parent_id"

Checkout coreyward's answer to the question here: Creating a model that has a tree structure

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"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文