[英]Rails: has_many and belongs_to
我的應用程序中有兩個模型:
位置:
class Position < ActiveRecord::Base
belongs_to :report_to_position, class_name: 'Position', foreign_key: 'report_to_position_id'
has_many :employees
end
雇員:
class Employee < ActiveRecord::Base
belongs_to :position
def boss
self.position.report_to_position.employee
end
end
正如您在boss
getter中看到的那樣,我需要在這種關系中employee
一名employee
。 問題是Position
班級有很多employees
。 我怎么能用這種模型邏輯得到一個對象(許多員工的老板)?
謝謝!
你不能得到與此相關聯設置的老板,但你可以得到一個老板。 那就是:你可以得到上級。 Position
類has_many :employees
,這給您兩個問題:
Employee
類中沒有什么可以說“這是我的直接上級”。 Position
類中沒有什么可以說“這個人是老板”。 那可能沒關系; 如果可以為給定的Employee
獲得(基本上是隨機的)上級,則您的boss方法可以如下所示:
def boss
self.position.report_to_position.employees.first
end
總體而言,我會重新考慮您的架構。 可以將組織結構圖和員工數據分開,這是可以的,但是您應該考慮通過自連接將上司/下屬的關聯轉移到Employee
本身:
class Employee < ActiveRecord::Base
has_many :subordinates, class_name: "Employee", foreign_key: "boss_id"
belongs_to :boss, class_name: "Employee"
belongs_to :position
end
結構體
為了幫助定義Alex P
的答案,您需要查看如何在關聯和表中定義 boss
記錄。
我看到的問題是,因為您所有的employee
關聯數據都相同,所以您無法確定誰是“老板”,因此您遇到了問題
有兩種方法可確保定義了boss
關聯:
- 在
ActiveRecord
關聯中- 在數據庫/
Model
-
協會
可能最可靠的方法是使用association
,如Alex P
:
#app/models/employee.rb
Class Employee < ActiveRecord::Base
belongs_to :boss, class_name: "Employee"
has_one :boss, class_name: "Employee", foreign_key: "boss_id"
end
-
模型
我要做的方法是使用Ancestry
gem-
#app/models/employee.rb
Class Employee < ActiveRecord::Base
has_ancestry
end
這必須與稱為ancestry
( string
)的數據表列結合:
這將使您可以給每位employee
一個父母 (可以是老板或經理等)。 該設置的優點在於您可以創建一個真正的“樹”結構-員工將能夠根據需要擁有多個經理/老板
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.