2016-04-23 90 views
2

我有兩個模型,Person和Business,以及一個連接表。如何創建不同類型的has_many:通過與兩個模型的關係?

class Person < ActiveRecord::Base 
    has_many :person_businesses 
    has_many :businesses, through: :person_businesses 
end 

class Business < ActiveRecord::Base 
    has_many :person_businesses 
    has_many :people, through: :person_businesses 
end 

class PersonBusiness < ActiveRecord::Base 
    belongs_to :person 
    belongs_to :business 
end 

我想要有多種方式來關聯一個企業和一個人,但。例如,一個企業可以有一個人作爲員工和客戶。

我該如何對此進行建模?

我認爲給person_businesses命名的角色添加一個列,這將成爲與關係類型相對應的枚舉,但我仍然不知道如何編寫關係。

+0

難道您不能在PersonBusiness中添加一列來識別此問題嗎?例如,如果PersonBusiness有員工:布爾值,它將顯示該員工是否是員工。在這種情況下,你的建模是正確的。 –

回答

2

所以我想我找到了我的問題的答案。我從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 
相關問題