Ruby on rails开发从头来(五十八)- ActiveRecord基础(自关联)
Posted on 2008-05-07 10:24 Cure 阅读(2771) 评论(1) 编辑 收藏 举报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"