Rails Model has_many with multiple foreign_keys

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

    I prefer to use scopes for this issue. Like this:

    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'
    
      scope :children_for, lambda {|father_id, mother_id| where('father_id = ? AND mother_id = ?', father_id, mother_id) }
    end
    

    This trick make it easy to get children without use instances:

    Person.children_for father_id, mother_id
    
    0 讨论(0)
  • 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?

    0 讨论(0)
提交回复
热议问题