这应该很容易。我想我一定会被命名。
“经理”和“下属”(员工)都属于“人”类。
这就是我所拥有的:
class Person < ActiveRecord::Base
has_many :person_manager_assignments
has_many :managers, :through => :person_manager_assignments
has_many :subordinates, :through => :person_manager_assignments
end
class PersonManagerAssignment < ActiveRecord::Base
has_one :subordinate, :class_name => "Person", :foreign_key => "id", :primary_key => 'person_id'
has_one :manager, :class_name => "Person", :foreign_key => "id", :primary_key => 'manager_id'
end
这对于检查和分配经理非常有用。
关于下属,我抓住了这个问题。它返回人的自我,而不是他们的下属:
p.subordinates
Person Load (0.5ms) SELECT "people".* FROM "people" INNER JOIN "person_manager_assignments" ON "people"."id" = "person_manager_assignments"."person_id" WHERE "person_manager_assignments"."person_id" = 15973
请参阅WHERE子句中与“person_id”匹配的位?我需要它是“manager_id”,但是弄乱PersonManagerAssignment关联foreign_key和primary_key值似乎没有帮助。
有什么想法吗?
答案 0 :(得分:2)
答案基本上就在这里:http://railscasts.com/episodes/163-self-referential-association
所以我认为你需要这个:
class Person < ActiveRecord::Base
has_many :person_manager_assignments
has_many :managers, :through => :person_manager_assignments
has_many :subordinate_relationships, :class_name=>"PersonManagerAssignment", :foreign_key=>"manager_id"
has_many :subordinates, :through => :subordinate_relationships, :source=>:person
end
和
class PersonManagerAssignment < ActiveRecord::Base
belongs_to :person
belongs_to :manager, :class_name=>"Person"
end
摇滚。
答案 1 :(得分:0)
我猜你的PersonManagerAssignment表中有一个person_id和一个manager_id以及模型中的关联,如has_one:person和has_one:manager。如果是这种情况,我建议更改此关联
has_one :person
到这个
has_one :subordinate, :class_name => "Person", :foreign_key => "person_id"
然后你的has_many:下属应该按预期工作。
答案 2 :(得分:0)
class Person < ActiveRecord::Base
has_many :subordinates :through => :person_manager_assignments
has_many :managers, :through => :person_manager_assignments
end
class PersonManagerAssignment < ActiveRecord::Base
belongs_to :subordinate, :class_name => 'Person'
belongs_to :manager, :class_name => 'Person'
end