How does the Activersecord Rails table refer to itself?

everything. I have an idea to use Activerecord to implement something strange, as in the example below:

SystemInfo < ActiveRecord::Base belongs_to :SystemInfo end 

The idea is that system A can contain system B as its child. Therefore, I will generate the application skeleton as:

  script/generate scaffold SystemInfo parent_id:integer name:string 

and then when I insert System A, I will use System A ID as System B parent_id (System A parent_id will be "nil" and when I use the command as follows:

 sysA = SystemInfo.find_by_id(1) # Get System A 

I think it’s possible to get System A, and this is a child of System B. Similarly:

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

Could you offer me guidance for implementing this idea? I think this is a fairly common idea, and we should do it .;)

+6
ruby ruby-on-rails activerecord
source share
2 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> 
+15
source share

See acts_as_tree . I used it back on the project, so I'm not sure how much it has changed since then, but I think it does what you are looking for.

+2
source share

All Articles