我如何建立belongs_to :through(我知道这是无效的)关系?例如:一家公司有很多部门。一个部门有很多团队。有些团队是跨职能的,因此他们可以跨越许多部门(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
我如何从团队中获得公司。有什么好方法可以做到这一点?第一个应该有效,但我可以或应该尝试在模型中作为一种关系来做吗?
class Team < ActiveRecord::Base
has_and_belongs_to_many :departments
def company
departments.first.company
end
end
或者
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