views:

260

answers:

2

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

A: 

Look into acts_as_tree. I used it on a project way back, so I'm not sure how much it has changed since then, but I think it does what you're looking for.

zenazn
+4  A: 

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>
erik
Thank you, Erik. I have tried your solution but when I retest it in console it show something like below: reload! Reloading... => true >> SysInfo.find(:all) SysInfo.find(:all) ArgumentError: Unknown key(s): classI use Rails 2.3.3. Could you explain me why couldn't I do like you?
Teerasej
I found what I have to improve. I need to use ':class_name' instead of ':class' (may be, it's from new Rails version). Thank you very much, Erik! I choose your answer! ;)
Teerasej
Thanks, Teerasej. I updated the answer to be correct.
erik