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. ;)
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With