chipmunk chipmunk - 3 months ago 16
Ruby Question

has_many relationship on same model, multiple field names

I have a model

Company
which has the fields:

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


and
CompanyList


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


I have
Curriculum
model, where there could be 2 types of company lists say
hiring_company_list
,
sponsoring_company_list
.

How should the
Curriculum
model have the same
has_many
on
CompanyList
but with different names so that each list ID could be different (not alias). Also the
Curriculum
should have only one type of each company list.

Answer

So you want on Curriculum have two has_many that point to the Company model through different names right?, Well why not just use a has_many through association?

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

This way you can easily access the different types of company lists from Curriculum:

curriculum = Curriculum.create
curriculum.sponsoring_company_list
curriculum.hiring_company_list