ActiveRecord外键引用同一表中的主键

时间:2015-07-23 18:32:41

标签: ruby-on-rails activerecord

我想知道如何创建一个具有外键的模型,该外键引用同一个表中的主键?例如,考虑Tom是Beth和Bucky的父母,其中Persons表的字段为parent_id:

Persons table
|  id  |   name  | parent_id |
|----  |-------  |---------- |
|  1   |   Tom   |    null   |
|  2   |  Beth   |     1     |
|  3   | Bucky   |     1     |


class Person < ActiveRecord::Base
  belongs_to :person, :foreign_key => 'parent_id'
  has_many :persons, :foreign_key => 'parent_id'
end

上述工作或是否有其他方法可以正确地将其关联起来?

0 个答案:

没有答案
相关问题