我试图通过自连接(基于@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他在我的本地安装上进行全面练习。你可以试试看,看看你会得到什么样的结果。 – 2011-06-21 14:08:07
另外,如果你喜欢走这条路,你应该看看这个问题。它显示了你正在做的更多的事情,虽然我仍然发现自己有点缺乏清晰度(fyi-问题在问题中得到了回答):http://stackoverflow.com/questions/6426383/rails-协会使用数据的关联表 – 2011-06-21 15:45:44