2012-05-24 57 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