我有以下两个简单的类:
class Person < ActiveRecord::Base
has_many :parent_child_assignments
has_many :children, :through => :parent_child_assignments
has_many :parents, :through => :parent_child_assignments
end
class ParentChildAssignment < ActiveRecord::Base
belongs_to :parent, :class_name => "Person"
belongs_to :child, :class_name => "Person"
end
从以下rails命令创建
rails generate model Person name:string
rails generate model ParentChildAssignment parent_id:integer child_id:integer
我可以得到一个方向(joe.children或joe.parents)工作,但不是两个
之前有人问过这个问题,但我找不到。
提前致谢。
答案 0 :(得分:0)
这些类应该如下:
class Person < ActiveRecord::Base
has_many :parent_child_assignments_as_parent, class_name: 'ParentChildAssignment', :foreign_key => :parent_id
has_many :parent_child_assignments_as_child, class_name: 'ParentChildAssignment', :foreign_key => :child_id
has_many :children, :through => :parent_child_assignments_as_parent
has_many :parents, :through => :parent_child_assignments_as_child
end
class ParentChildAssignment < ActiveRecord::Base
belongs_to :parent, :class_name => "Person", :foreign_key => :parent_id
belongs_to :child, :class_name => "Person", :foreign_key => :child_id
end