rails habtm and belongs_to:through

时间:2012-05-24 03:02:01

标签: ruby-on-rails

如何设置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

1 个答案:

答案 0 :(得分:0)

你想要的关系已经存在。如果您知道所有部门都属于同一家公司,那么

my_team.departments.first.company