多个外键指向一个模型

阅读更多
多个外键指向一个模型,比较极端的例子:

http://stackoverflow.com/questions/307581/rails-model-has-many-with-multiple-foreign-keys

class Person < ActiveRecord::Base
  belongs_to :father, :class_name => 'Person'
  belongs_to :mother, :class_name => 'Person'
  has_many :children_of_father, :class_name => 'Person', :foreign_key => 'father_id'
  has_many :children_of_mother, :class_name => 'Person', :foreign_key => 'mother_id'
end


注:
  • class_name => 'Person','Person'必须是字符串,不能是符号,而且大小写必须与模型类一样
  • has_many必须指定foreign_key



引用:someone.father
someone.mother
someone.children_of_father
someone.children_of_mother

你可能感兴趣的:(Rails,ActiveRecord)