试图模拟铁路中两个人之间的关系

时间:2013-11-23 01:03:59

标签: ruby-on-rails-4 jointable

我有以下两个简单的类:

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)工作,但不是两个

之前有人问过这个问题,但我找不到。

提前致谢。

1 个答案:

答案 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