Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jsf-2/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails';Activerecord表是否引用自身?_Ruby On Rails_Ruby_Activerecord - Fatal编程技术网

Ruby on rails Rails';Activerecord表是否引用自身?

Ruby on rails Rails';Activerecord表是否引用自身?,ruby-on-rails,ruby,activerecord,Ruby On Rails,Ruby,Activerecord,各位。我有一个想法,使用Activerecord实现一些奇怪的东西,如下面的示例: SystemInfo < ActiveRecord::Base belongs_to :SystemInfo end 然后,当我插入系统A时,我将使用系统A的ID作为系统B的父\u ID(系统A的父\u ID将等于'nil'。当我像这样使用命令时: sysA = SystemInfo.find_by_id(1) # Get System A 我认为这可能得到系统A,它是子系统B。类似于: sysA

各位。我有一个想法,使用Activerecord实现一些奇怪的东西,如下面的示例:

SystemInfo < ActiveRecord::Base
  belongs_to :SystemInfo

end
然后,当我插入系统A时,我将使用系统A的ID作为系统B的父\u ID(系统A的父\u ID将等于'nil'。当我像这样使用命令时:

sysA = SystemInfo.find_by_id(1) # Get System A
我认为这可能得到系统A,它是子系统B。类似于:

sysA.childrens # Get System B and other SystemInfo which has parent_id == 1 (System A's ID)

你能为我提供实施这一想法的指导方针吗?我认为这是一个相当普遍的想法,我们应该有可能做到这一点。

调查一下。我以前在一个项目中使用过它,所以我不确定从那时起它有多大的变化,但我认为它符合您的要求。

您的想法是正确的

class SystemInfo < ActiveRecord::Base
  belongs_to :parent, :class_name => 'SystemInfo'
  has_many :children, :class_name => 'SystemInfo', :foreign_key => 'parent_id'
end

s = SystemInfo.find(1)
s.children
# => [...]
s.parent
# => <SystemInfo>
classsysteminfo'SystemInfo'
有多个:子项,:class\u name=>'SystemInfo',:foreign\u key=>'parent\u id'
结束
s=SystemInfo.find(1)
s、 孩子们
# => [...]
s、 母公司
# => 

谢谢你,埃里克。我已经尝试过你的解决方案,但当我在控制台中重新测试它时,它会显示如下内容:重新加载!重新加载…=>true>>SysInfo.find(:all)SysInfo.find(:all)ArgumentError:未知键:类I使用Rails 2.3.3。你能解释一下为什么我不能像你一样吗?我发现了我需要改进的地方。我需要使用“:class_name”而不是“:class”(可能是,它来自新的Rails版本)。非常感谢你,埃里克!我选择你的答案!;)
class SystemInfo < ActiveRecord::Base
  belongs_to :parent, :class_name => 'SystemInfo'
  has_many :children, :class_name => 'SystemInfo', :foreign_key => 'parent_id'
end

s = SystemInfo.find(1)
s.children
# => [...]
s.parent
# => <SystemInfo>