Perhaps there is a situation where a record is associated with another record in a table, for example, every employee in the company has superiors and subordinates, and they are employees, and you can use the employee class in rails:
Class Employee < ActiveRecord::Base
Belongs_to:manager,
: class_name => "Employee",
: Foreign_key = > "manager_id"
belongs_to:mentor,
: class_name => "Employee",
foreign_key => "mentor_id
" Has_many:mentored_employees,
: class_name => "Employee"
: Foreign_key => "mentor_id"
Has_many: Managed_employees,
: class_name => "Employee"
: Foreign_key => "manager_id" End
Let's use some data, where employees Clem and Dawn both have superiors and subordinates:
Employee.delete_all
adam = employee.create (: ID => 1,: Name => "Adam")
Beth = employee.create (: ID => 2, : Name => "Beth")
Clem = employee.new (: Name => "Clem")
Clem.manager = Adam
clem.mentor = Beth
C lem.save!
Dawn = employee.new (: Name => "Dawn")
Dawn.manager = Adam
dawn.mentor = Clem
dawn.save!
Now we can answer by association, "who is X's subordinate?" "," Who is the superior of Y? ”。
P Adam.managed_employees.map {|e| e.name} # => ["Clem", "Dawn"]
P adam.mentored_employees # => []
p DAWN.M Entor.name # => "Clem"