Rails Model has_many with multiple foreign_keys

前端 未结 8 1071
说谎
说谎 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:34

    My answer to Associations and (multiple) foreign keys in rails (3.2) : how to describe them in the model, and write up migrations is just for you!

    As for your code,here are my modifications

    class Person < ActiveRecord::Base
      belongs_to :father, :class_name => 'Person'
      belongs_to :mother, :class_name => 'Person'
      has_many :children, ->(person) { unscope(where: :person_id).where("father_id = ? OR mother_id = ?", person.id, person.id) }, class_name: 'Person'
    end
    

    So any questions?

提交回复
热议问题