ahnbizcad
ahnbizcad

Reputation: 10797

Rails - Using multple has_many through: associations joining same two models. Redundant has_many through:

Would association person and company through employment AND through interviewing be bad practice? Why, specifically? And does that answer apply to databases in general, not just rails?

Example:

employment.rb

class Employment < ActiveRecord::Base
    belongs_to :people
    belongs_to :companies
end

interview.rb

class Interview < ActiveRecord::Base
    belongs_to :people
    belongs_to :companies
end

person.rb

class Person < ActiveRecord::Base
    has_many :employments
    has_many :interviews
    has_many :companies, through: :employments
    has_many :companies, through: :interviews
end

company.rb

class Company < ActiveRecord::Base
    has_many :employments
    has_many :interviews
    has_many :companies, through: :employments
    has_many :companies, through: :interviews
end

Person and Company are associated through Employment, but also redundantly through Interview.

Upvotes: 0

Views: 134

Answers (1)

MrTheWalrus
MrTheWalrus

Reputation: 9700

There's nothing wrong with having two models having multiple associations, including multiple associations of the same type. You will want to give the associations unique names, though - otherwise when you called (for instance) @person.companies, you wouldn't know what you were going to get - companies through employments, or companies through interviews.

I believe this question has a decent example: ruby on rails has_many :through association which has two columns with same model

Upvotes: 1

Related Questions