【问题标题】:rails belongs_to through via associationrails belongs_to 通过关联
【发布时间】:2012-04-21 22:49:14
【问题描述】:

我正在使用 rails 3.0 并试图找出设置 belong_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

但是,我想知道我是否可以通过关联进行上述操作。

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多