单个ActiveRecord has_one关系的多个外键

时间:2015-11-04 21:34:32

标签: ruby-on-rails activerecord

我有一个与办公室和部门相关的模型。

class DataForm < ActiveRecord::Base
  belongs_to :office
  belongs_to :department
end

我还有第三个监督许多办公室/部门组合的模型。

class ManagementGroup < ActiveRecord::Base
   belongs_to :office
   belongs_to :department
end

我怎么说DataForm与ManagementGroup有关联,其中办公室和部门彼此同步。

class DataForm < ActiveRecord::Base
  belongs_to :office
  belongs_to :department
  # how would I get the below association to work 
  has_one :management_group, foreign_key: [:office_id, :department_id]
end

1 个答案:

答案 0 :(得分:0)

我怎么说DataForm与管理组有关联,其中办公室和部门彼此同步。你不能这样做。相反,你重组它:

  • DataForm属于ManagementGroup
  • ManagementGroup属于_ :office:department

因此,您可以通过查看:office :department来确定DataForm的{​​{1}}和ManagementGroup

然后,您可以访问belongs_to的办公室,例如:

DataForm

或者更好,使用委托人。示例如下:

@data_form.management_group.office

然后,您可以这样做:

class DataForm < ActiveRecord::Base
  belongs_to :management_group
  delegate :office, to: :management_group
  delegate :department, to: :management_group
end

class ManagementGroup < ActiveRecord::Base
   belongs_to :office
   belongs_to :department
   has_many :data_forms
end