Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can Rails' Activerecord table refer to itself?

everyone. I have an idea to use Activerecord to implement something strange like the example below:

SystemInfo < ActiveRecord::Base
  belongs_to :SystemInfo

end

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

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

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. ;)

like image 956
Teerasej Avatar asked Jul 30 '09 15:07

Teerasej


1 Answers

You have the right idea.

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>
like image 85
erik Avatar answered Oct 07 '22 06:10

erik