在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 #=> [#<Employee id:...>]
难道我做错了什么?
没有找到相关结果
已邀请:
4 个回复
澜悍景哭苟
和
回调:
这应该可以使您能够使用
您可能要在回调中使用
的
实例 您也可以阅读有关此解决方案的问题
宦哨抹存胳
这样一来,从编码的角度来看,它不会变得不必要的复杂,并且您可以使用标准集合来访问它,它将为您适当地建立连接,而无需管理它们。因此,这两个集合都应该工作。
而且您不必管理任何其他变量。合理?它添加了一个表,但提高了清晰度。
钨蜡唤喉晤
现在,您可以执行以下操作:
注意:通常要求一个人离开公司,向两个经理报告:-)
课刊灭似
尽管该解决方案有效-通过将关联与\“ rel_type \”捆绑在一起,我还是有些困惑。在这种情况下-我会说rel_type是冗余的,并且该关系应按以下方式映射:
在这种情况下,关联映射应该更简单一些。