Связь «многие-ко-многим» с несколькими самосоединениями в ActiveRecord

Я пытаюсь реализовать множественные отношения между записями одной и той же модели посредством самосоединения (на основе ответа @ Shtéf ). У меня есть следующие модели

create_table :relations, force: true do |t|
  t.references :employee_a
  t.string     :rel_type
  t.references :employee_b
end

class Relation < ActiveRecord::Base
  belongs_to :employee_a, :class_name => 'Employee'
  belongs_to :employee_b, :class_name => 'Employee'
end

class Employee < ActiveRecord::Base
  has_many :relations, foreign_key: 'employee_a_id'
  has_many :reverse_relations, class_name: 'Relation', foreign_key: 'employee_b_id'

  has_many :subordinates, through: :relations, source: 'employee_b', conditions: {'relations.rel_type' => 'manager of'}
  has_many :managers, through: :reverse_relations, source: 'employee_a', conditions: {'relations.rel_type' => 'manager of'}
end

С этой настройкой я могу успешно получить доступ к спискам подчиненных и менеджеров для каждой записи. Однако мне трудно создать отношения следующим образом

e = Employee.create
e.subordinates.create
e.subordinates #=> []
e.managers.create
e.managers #=> []

Проблема в том, что он не устанавливает тип отношений, поэтому я должен написать

e = Employee.create
s = Employee.create
e.relations.create employee_b: s, rel_type: 'manager of'
e.subordinates #=> [#]

Я что-то делаю не так?

8
задан Community 23 May 2017 в 11:44
поделиться