所以我想我找到了我的问题的答案。我从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有员工:布尔值,它将显示该员工是否是员工。在这种情况下,你的建模是正确的。 –