简体   繁体   English

轨道habtm和belongs_to:通过

[英]rails habtm and belongs_to :through

How do I set up a belongs_to :through (which I know is not valid) relationship? 我如何建立一个Relationships_to:through(我知道这是无效的)关系? 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). 而且有些团队是跨职能的,因此他们可以跨越多个部门(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 如果您知道所有部门都属于同一公司,则可以执行

my_team.departments.first.company

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM