【问题标题】:has_many relationship on same model, multiple field nameshas_many 同一模型上的关系,多个字段名称
【发布时间】:2016-08-26 18:01:45
【问题描述】:

我有一个模型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 模型,其中可能有两种类型的公司列表,例如hiring_company_listsponsoring_company_list

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

【问题讨论】:

  • 如果这些模型之间的关系不同,则表明您需要重新设计它。也许CompanyListCurriculumList 可以是List 类型(继承自它),并且在这些模型中的每一个中,您都定义了唯一的关系。
  • 好的。有没有办法让我在同一模型上使用has_many,但字段名称不同?
  • 你能说得更具体点吗?
  • 我想在我的curriculum 中使用has_many company_list,但我想拥有2 个这样的关联,但名称不同,因为它们是不同的字段。我该怎么做?
  • 我看到有一个新的答案。我试图让你向我们描述你所说的“不同的名字”和“不同的领域”是什么意思。有一个Curriculum 模型的例子会有所帮助。

标签: ruby-on-rails ruby activerecord associations mongoid


【解决方案1】:

所以你想在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 = Curriculum.create
curriculum.sponsoring_company_list
curriculum.hiring_company_list

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2019-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-17
相关资源
最近更新 更多