或許存在這樣的情況,在一個表中,一條記錄關聯到表中的另一條記錄,例如,公司中的每個雇員都有上級和下級,而他們同時又是雇員,在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"