Rails Model has_many with multiple foreign_keys

前端 未结 8 1092
说谎
说谎 2020-11-28 06:04

Relatively new to rails and trying to model a very simple family \"tree\" with a single Person model that has a name, gender, father_id and mother_id (2 parents). Below is b

8条回答
  •  余生分开走
    2020-11-28 06:12

    Not a solution to the general question as stated ("has_many with multiple foreign keys"), but, given a person can either be a mother or a father, but not both, I would add a gender column and go with

      has_many :children_of_father, :class_name => 'Person', :foreign_key => 'father_id'
      has_many :children_of_mother, :class_name => 'Person', :foreign_key => 'mother_id'
      def children
        gender == "male" ? children_of_father : children_of_mother
      end
    

提交回复
热议问题