带有多个外键的 Rails 模型 has_many [英] Rails Model has_many with multiple foreign_keys

查看:30
本文介绍了带有多个外键的 Rails 模型 has_many的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Rails 相对较新,并尝试使用具有姓名、性别、father_id 和 Mother_id(2 个父母)的单个 Person 模型对一个非常简单的家庭树"进行建模.下面基本上是我想要做的,但显然我不能重复 has_many 中的 :children(第一个被覆盖).

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 basically what I want to do, but obviously I can't repeat the :children in a has_many (the first gets overwritten).

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

是否有一种简单的方法可以将 has_many 与 2 个外键一起使用,或者根据对象的性别更改外键?或者还有其他/更好的方法吗?

Is there a simple way to use has_many with 2 foreign keys, or maybe change the foreign key based on the object's gender? Or is there another/better way altogether?

谢谢!

推荐答案

在 IRC 上找到一个简单的答案,似乎有效(感谢 Radar):

Found a simple answer on IRC that seems to work (thanks to Radar):

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'
  def children
     children_of_mother + children_of_father
  end
end

这篇关于带有多个外键的 Rails 模型 has_many的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆