对 Rails 来说相对较新,并尝试使用具有姓名、性别、father_id 和 mother_id(2 个父母)的单个 Person 模型来建模非常简单的家庭“树”。下面基本上是我想做的,但显然我不能在 has_many 中重复 :children (第一个被覆盖)。
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 个外键一起使用,或者可以根据对象的性别更改外键?或者还有另一种/更好的方法吗?
Thanks!
在 IRC 上找到了一个似乎有效的简单答案(感谢 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)