如何Rails的ActiveRecord的表是指本身? [英] How can Rails' Activerecord table refer to itself?
问题描述
大家。我有一个想法,使用ActiveRecord来实现一些奇怪的如下面的例子:
everyone. I have an idea to use Activerecord to implement something strange like the example below:
SystemInfo < ActiveRecord::Base
belongs_to :SystemInfo
end
我们的想法是,系统A可以包含系统B作为其子。因此,我将生成应用程序的框架为:
The idea is, System A can contain System B as its child. So I will generate application's skeleton as:
script/generate scaffold SystemInfo parent_id:integer name:string
然后,当我插入系统A,我将使用系统A的ID作为系统B的PARENT_ID(系统A的PARENT_ID就等于'零',当我使用的命令是这样的:
and then, when I insert System A, I will use System A's ID as System B's parent_id (System A's parent_id will equal to 'nil'. and when I use the command like this:
sysA = SystemInfo.find_by_id(1) # Get System A
我认为这是可能获得系统A,和它的孩子,系统B.类似的:
I think this is possible to get System A, and it's child, System B. Similar to:
sysA.childrens # Get System B and other SystemInfo which has parent_id == 1 (System A's ID)
您可以建议指引我实现这个想法?我认为这是相当普遍的想法,我们应该能够做到这一点。 ;)
Could you suggest guideline for me to implement this idea? I think this is quite common idea and we should possible to do it. ;)
推荐答案
您有正确的想法。
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>
这篇关于如何Rails的ActiveRecord的表是指本身?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!