How do I set up a belongs_to :through (which I know is not valid) relationship? For instance: A company has many departments. A department has many teams. And some teams are cross-functional so they can span many departments (habtm).
class Company < ActiveRecord::Base
has_many :departments
has_many :teams, through: :departments
end
class Department < ActiveRecord::Base
belongs_to :company;
has_and_belongs_to_many :teams
end
class Team < ActiveRecord::Base
has_and_belongs_to_many :departments
end
How do I get company from team. What is a good way to do this? The first should work but can I or should I be trying to do it in the model as a relationship?
class Team < ActiveRecord::Base
has_and_belongs_to_many :departments
def company
departments.first.company
end
end
or
class Team < ActiveRecord::Base
has_and_belongs_to_many: departments
has_one :company, through: departments (<-- is this valid?, seems like this should be has_many but that's not right!)
end
The relationship you want is already there. If you know all the departments belong to the same company you can do