셀프 조인 (@Shtééf's answer 기준)을 통해 동일한 모델의 레코드간에 다중 관계를 구현하려고합니다. 다음 모델이 있습니다ActiveRecord에서 다중 셀프 조인을 사용하는 다 대다 연관
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 #=> [#<Employee id:...>]
내가 뭔가 잘못하고 있는가 작성해야?
그리고 belongs_to가 필요하다는 것은 완전히 확신 할 수는 없지만, t 설정할 시간이 없었습니다. 그는 내 로컬 설치에 전체 운동. 당신은 어떤 결과를 얻었는지에 상관없이 그것을 시도 할 수 있습니다. –
또한이 경로를 따라 가기를 원할 경우이 질문을 확인하십시오. 그것은 당신이하고있는 일들의 선을 따라 더 많이 보여 주지만, 나는 아직도 자신이 조금 부족하다는 선명도를 발견한다. (질문은 질문에 대답되어있다.) http://stackoverflow.com/questions/6426383/rails- 협회 - 사용 - 연관 테이블 - 데이터 테이블 –