2012-05-24 60 views
0

如何设置belongs_to:通过(我知道这是无效的)关系?例如:一家公司有很多部门。一个部门有很多团队。有些团队是跨职能的,因此他们可以跨越很多部门(habtm)。rails habtm和belongs_to:通过

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 

回答

0

你想要的关系已经存在。如果你知道所有部门属于同一家公司,你可以做

my_team.departments.first.company 
+0

感谢您的确认 – anu