如何创建不同类型的has_many:通过与两个模型的关系?

时间:2016-04-23 21:51:16

标签: ruby-on-rails rails-activerecord

我有两个模型,Person和Business,以及一个连接表。

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

但我希望有一种方法可以将一个企业与一个人联系起来。例如,企业可以将个人作为雇员和客户。

我将如何对此进行建模?

我考虑过将一个列添加到名为role的person_businesses,这将是一个与关系类型相对应的枚举,但我仍然不知道如何编写关系。

1 个答案:

答案 0 :(得分: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