has_many 同一模型上的关系,多个字段名称

has_many relationship on same model, multiple field names

我有一个模型 Company,其中包含以下字段:

  field :label,              type: String
  field :logo_url,           type: String
  field :status,             type: String
  belongs_to :company_lists, :class_name => 'Models::Persistence::CompanyList'

CompanyList

  field :label,            type: String
  field :status,           type: String
  has_and_belongs_to_many :companies, inverse_of: nil

我有 Curriculum 模型,其中可能有 2 种类型的公司列表,比如 hiring_company_listsponsoring_company_list

Curriculum 模型如何在 CompanyList 上具有相同的 has_many 但名称不同,以便每个列表 ID 可以不同(不是别名)。此外,Curriculum 每个公司列表应该只有一种类型。

所以你想在 Curriculum 上有两个 has_many 通过不同的名称指向 Company 模型对吗?为什么不使用 has_many through 关联?

class CurriculumCompanyList < ActiveRecord::Base
  belongs_to :company
  belongs_to :curriculum
end

class Curriculum < ActiveRecord::Base
  has_many :curriculum_company_lists
  #here could be has_many as well if you point directly to companies instead of companylist
  has_one :hiring_company_list, through: :curriculum_company_lists
  has_one :sponsoring_company_list, through: :business_line_subscriptions
end

class CompanyList < ActiveRecord::Base
  has_many :curriculum_company_lists
  has_many :curriculums, through: :curriculum_company_lists
end

这样您就可以轻松地从课程中访问不同类型的公司列表:

curriculum = Curriculum.create
curriculum.sponsoring_company_list
curriculum.hiring_company_list