2016-04-23 67 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 
相关问题