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

查看:97
本文介绍了带有多个foreign_keys的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

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

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