或许存在这样的情况,在一个表中,一条记录关联到表中的另一条记录,例如,公司中的每个雇员都有上级和下级,而他们同时又是雇员,在Rails中你可以这样使用Employee类:
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
让我们使用一些数据,这里雇员Clem和Dawn都有上级和下级:
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
clem.save!
dawn = Employee.new(:name => "Dawn")
dawn.manager = adam
dawn.mentor = clem
dawn.save!
现在我们可以通过关联,来回答“X的下属是谁?”,“Y的上级是谁?”。
p adam.managed_employees.map {|e| e.name} # => [ "Clem", "Dawn" ]
p adam.mentored_employees # => []
p dawn.mentor.name # => "Clem"