寻找递归模型中循环引用的简单测试

发布于 2024-09-28 01:38:00 字数 462 浏览 7 评论 0原文

我有一个模型,表示由组件组成的组件,组件(就其本身而言)也可以是组件。它看起来有点像这样:

class Component < ActiveRecord::Base
  belongs_to :assembly, :class_name => "Component", :foreign_key => :assembly_id
  has_many :pieces, :class_name => "Component", :foreign_key => :assembly_id
end

我想确定当我将组件添加到程序集中时,添加的不是程序集本身,也不是链上的另一个程序集。实际上,无论向下多少层,程序集都无法包含自身。

我的想法是在保存组件时向上遍历树以查找组件本身作为父级、祖级等。我试图避免循环引用。

有没有一种“简单的、Rails 式的”方法来做到这一点?还有其他建议吗?

I have a model that represents an assembly that is made up of components, components may (in their own right) also be assemblies. It looks a little like this:

class Component < ActiveRecord::Base
  belongs_to :assembly, :class_name => "Component", :foreign_key => :assembly_id
  has_many :pieces, :class_name => "Component", :foreign_key => :assembly_id
end

I want to be certain that when I add a component to the assembly that what's being added isn't the assembly itself, or another assembly up the chain. Effectively, an assembly can't contain itself, regardless of how many levels down you go.

My thought is to traverse the tree going up when a component is saved to look for the component itself as a parent, grandparent, etc. I'm trying to avoid circular references.

Is there an "easy, Rails-ish" way to do this? Any other suggestions?

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

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

发布评论

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

评论(1

御弟哥哥 2024-10-05 01:38:01

我根本不了解铁轨。然而,听起来你几乎已经回答了你自己的问题。

当前的问题自然适合递归解决方案。

您说您已经将这些程序集引用视为一棵树。

您有一个程序集作为树的根,并有一个分支列表作为其组件。

您可以使用 contains(Node, ListOfAssemblies) 函数,当且仅当 Node 下面没有节点包含 中的任何程序集时,该函数才返回 true程序集列表。该函数可以递归地调用自身,直到到达叶子并返回。

您只需要弄清楚(1)其工作原理的逻辑以及(2)如何在代码中表示您的组件和程序集。

祝你好运!

I don't know rails at all. However, it sounds like you've nearly answered your own question.

The question at hand naturally lends itself to a recursive solution.

You say that you already think of these assembly references as being a tree.

You have a single assembly as the root of the tree, and a list of branches as it's components.

You could have a function contains(Node, ListOfAssemblies) that returns true if and only if no node beneath Node contains any assembly in ListOfAssemblies. This function could recursively call itself until it gets to a leaf and returns.

You just need to work out (1) the logic of how this works and (2) how your components and assemblies will be represented in code.

Good luck!

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