rails belongs_to通过via association

时间:2012-04-21 22:49:14

标签: activerecord associations rails-activerecord has-many belongs-to

我在rails 3.0上试图弄清楚什么是设置belongs_to的正确方法:通过关系(我知道这是不可能的)。这是一个例子:

class ParentCompany < ActiveRecord::Base
  has_many :subsidiaries
  has_many :employees, :through => :subsidiaries
end

class Subsidiary < ActiveRecord::Base
  belongs_to :parent_company
  has_many :employees
end

class Employee < ActiveRecord::Base
  belongs_to :subsidiary
  belongs_to :parent_company, :through :subsidiary # <-- I know this is invalid
end

我知道我可以通过以下方式解决它:

class Employee < ActiveRecord::Base
  def parent_company
    subsidiary.parent_company
  end
end

但是,我想知道我是否可以通过协会来完成上述工作。

1 个答案:

答案 0 :(得分:1)

您可以使用delegate来完成此操作,而无需使用关联

class Employee < ActiveRecord::Base
  belongs_to :subsidiary
  delegate :parent_company, to: :subsidiary
end