所以我想我找到了我的問題的答案。我從this answer中得到了大部分的改動。
class Business < ActiveRecord::Base
has_many :person_businesses
has_many :people, through: :person_businesses
end
class Person < ActiveRecord::Base
has_many :person_businesses
has_many :employees, through: :employee_businesses, source: :business
has_many :employee_businesses, -> { where(person_type: 'employee') }, class_name: 'PersonBusiness'
has_many :customers, through: :customer_businesses, source: :business
has_many :customer_businesses, -> { where(business_type: 'customer') }, class_name: 'PersonBusiness'
end
class PersonBusiness < ActiveRecord::Base
enum person_type: { employee: 0, customer: 1 }
belongs_to :person
belongs_to :business
end
此功能現在可用,但看起來並不容易擴展。如果有人對如何簡化它有什麼建議,我很樂意看到它。
編輯:
我一直在繼續工作在這個問題上,有一個簡單的設置。我也改變了條件,因爲使用where
和枚舉導致它總是返回0 (more information for those that are interested)。
class Business < ActiveRecord::Base
has_many :person_businesses
has_many :people, through: :person_businesses
end
class Person < ActiveRecord::Base
has_many :person_businesses
has_many :employees, -> { PersonBusiness.employee }, through: :person_businesses, source: :business
has_many :customers, -> { PersonBusiness.customer }, through: :person_businesses, source: :business
end
class PersonBusiness < ActiveRecord::Base
enum person_type: { employee: 0, customer: 1 }
belongs_to :person
belongs_to :business
end
難道您不能在PersonBusiness中添加一列來識別此問題嗎?例如,如果PersonBusiness有員工:布爾值,它將顯示該員工是否是員工。在這種情況下,你的建模是正確的。 –